var userId = '';
$.ajax({
    type: "post",
    url: "/users/getUserTheme",
    dataType: 'json',
    async:false,
    success: function (res) {
        var data = res.object;
        userId = data.userId;
    }
})
//获取国际语言标志
var type = getCookie("language");
var qzhb='';
if (type == 'zh_CN') {
    qzhb = "此步骤为强制合并步骤，尚有步骤未转至此步骤，您不能继续转交下一步！";
} else if (type == 'en_US') {
    qzhb = "This step is a mandatory merge step, and there are still steps that you can't move forward. You can't proceed to the next step!";
} else if (type == 'zh_TW') {
    qzhb = "此步驟為強制合並步驟，尚有步驟未轉至此步驟，您不能繼續轉交下壹步！";
} else {
    qzhb = "此步骤为强制合并步骤，尚有步骤未转至此步骤，您不能继续转交下一步！";
}
var beforeToken = '';
/**********************与移动端交流时间控件调用*****************************************/
var timename = '';
function timeclick(e){
    timename = e.attr('name');
    if(e.attr('dates_format').indexOf('hh:mm:ss') == -1){
        var cs = '0';
    }else{
        var cs = '1';
    }
    if($.getQueryString("type") != 'EWC'){
        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
            try{
                window.webkit.messageHandlers.setSelectTime.postMessage({'num':cs});
            }catch(err){
                setSelectTime(cs);
            }

        } else if (/(Android)/i.test(navigator.userAgent)) {
            Android.setSelectTime(cs);
        }
    }
}
function autoclik(e) {
    var __this = $('#'+e.attr('target'))
    $.ajax({
        type: "post",
        url: "../../../document/updateCount",
        dataType: 'JSON',
        data:{
            id:__this.attr('uuid')

        },
        beforeSend : function(request) {
            if(beforeToken != ''){
                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
            }
        },
        success: function (obj) {
            if(obj.flag){
                __this.attr("value",obj.object.expressionStr)
            }
        }
    })
}
function timeclickjs(time){
    $('input[name='+ timename +']').val(time).trigger('propertychange');
}
var globalData = {};
var turn = function(){
    //alert("正在加载。。");
}
function covertToFormData(formdata){
    var data = {};
    if(formdata instanceof Array){
        formdata.forEach(function(v,i){
            data[v.key] =  v.value;
        });
    }
    return data;
}
function covertToPrcsOutSet(data){
    data = data.replace(/or/g,'||')
    data = data.replace(/and/g,'&&')
    return data;
}
function myTrim(x) {
    return x.replace(/^\s+|\s+$/gm,'');
}
function checkTileValue(item_value,rule,item_title){
    var checkpass = 0;
    if(item_value != ''){
        if(typeof item_value == 'string'){
            if(item_value.indexOf('-')>-1||item_value.indexOf(':')>-1){
                var item_value =  item_value
            }else{
                var item_value = parseFloat(item_value)  || item_value ;
            }
        }else{
            var item_value = parseFloat(item_value)  || item_value ;
        }


    }else{
        var item_value =  item_value;
    }
    if(item_title != ''){
        if(typeof item_title =='string'){
            if(item_title.indexOf('-')>-1||item_title.indexOf(':')>-1){
                var item_title = item_title
            }else{
                var item_title =  parseFloat(item_title) || item_title ;
            }
        }else{
            var item_title =  parseFloat(item_title) || item_title ;
        }

    }else{
        var item_title =  item_title;
    }
    var date = /^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/;
    var time = /^(((?!0000)[0-9]{4}-((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31)|([0-9]{2}(0[48]|[2468][048]|[13579][26])|(0[48]|[2468][048]|[13579][26])00)-02-29)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$/


    switch (rule) {
        case '=':
            var reDateTime = /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/;
            if(item_title == 'shu'&&!isNaN(item_value)){
                checkpass = 1;
            }else if(item_title == 'date'&& /^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/.test(item_value)){
                checkpass = 1;
            }else if(item_title == 'time'&& !reDateTime.test(item_value)){
                checkpass = 1;
            }else if (item_title == item_value) {
                checkpass = 1;
            }
            break;
        case '!=':
            var reDateTime = /^(?:19|20)[0-9][0-9]-(?:(?:0[1-9])|(?:1[0-2]))-(?:(?:[0-2][1-9])|(?:[1-3][0-1])) (?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]:[0-5][0-9]$/;
            if(item_title == 'shu'&&isNaN(item_value)){
                checkpass = 1;
            }else if(item_title == 'date'&& !/^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/.test(item_value)){
                checkpass = 1;
            }else if(item_title == 'time'&& reDateTime.test(item_value)){
                checkpass = 1;
            }else if (item_title != item_value) {
                checkpass = 1;
            }
            break;
        case '<>':
            if(date.test(item_title) && date.test(item_value)){
                if(new Date(item_title.replace(/-/g, "/")).getTime()!=new Date(item_value.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if(time.test(item_title) && time.test(item_value)){
                if(new Date(item_title.replace(/-/g, "/")).getTime()!=new Date(item_value.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if (item_title != item_value) {
                checkpass = 1;
            }
            break;
        case '>':
            if(date.test(item_title) && date.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()>new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if(time.test(item_title) && time.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()>new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if ( item_value >  item_title) {
                checkpass = 1;
            }
            break;
        case '<':
            if(date.test(item_title) && date.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()<new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if(time.test(item_title) && time.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()<new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if (item_value < item_title) {
                checkpass = 1;
            }
            break;
        case '<=':
            if(date.test(item_title) && date.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()<=new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if(time.test(item_title) && time.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()<=new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if (item_value <=  item_title) {
                checkpass = 1;
            }
            break;
        case '>=':
            if(date.test(item_title) && date.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()>=new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if(time.test(item_title) && time.test(item_value)){
                if(new Date(item_value.replace(/-/g, "/")).getTime()>=new Date(item_title.replace(/-/g, "/")).getTime()){
                    checkpass = 1;
                }
            }else if (item_value >=  item_title) {
                checkpass = 1;
            }
            break;
        case 'include':
            if(item_value==''){
                if(item_title==''){
                    checkpass = 1;
                }
            }else{
                item_value = String(item_value);
                if (item_value.indexOf(item_title) > -1) {
                    checkpass = 1;
                }
            }
            break;
        case 'exclude':
            if(item_value==''){
                if(item_title==''){
                    checkpass = 1;
                }
            }else{
                item_value = String(item_value);
                if(item_value!=''){
                    if (item_value.indexOf(item_title) == -1) {
                        checkpass = 1;
                    }
                }
            }
            break;
    }
    return checkpass;
}
function checkPrcOut(formdata,fromDataReject,cb){
    var msg = globalData.conditionDesc.split('\n')[1];
    var res = {
        flag:true,
        msg:""
    };
    if(msg){
        res.msg = msg;
    }else{
        res.msg =  '不符合条件！'
    }
    var prcsOut = globalData.prcsOut;
    var prcsOutSet = globalData.prcsOutSet;
    var prcsOutArr = prcsOut.split('\n');
    if(prcsOutArr.length == 1 && prcsOutSet == ''){
        prcsOutSet = '[1]';
    }
    if(prcsOutSet != ""){
        var prcsOutArr = prcsOut.split('\n');
        formdata = covertToFormData(formdata);


        prcsOutArr.forEach(function(v,i){
            if(v){
                var check_pass = 0;
                var titleValue = '';
                var arr_rule = v.split("'");
                var item_title = myTrim(arr_rule[1]);
                var item_con = myTrim(arr_rule[2]);
                var item_value = myTrim(arr_rule[3]);
                var item_pag = $('[Id="'+fromDataReject[item_title]+'"]')

                if(v.indexOf('[')<=-1){
                    if(item_pag.attr('data-type')=='macros'&&item_pag.attr('datafld')=='SYS_USERNAME'&&item_pag.attr('orgsignImg')==1){
                        if(item_pag.prev().find('img').attr('src')!=undefined&&item_pag.prev().find('img').attr('src')!=''&&item_pag.prev().find('img').attr('src').indexOf('AID')>=0){
                            titleValue = item_pag.prev().find('img').attr('src');
                        }else{
                            titleValue = formdata[fromDataReject[item_title]];
                        }
                    }else{
                        titleValue = formdata[fromDataReject[item_title]];
                        //针对宏主角色列表控件  需要对titleValue进行处理
                        if(item_pag.attr('data-type')=='macros'&&item_pag.attr('datafld')=='SYS_LIST_PRIV_ONLY'){
                            titleValue=item_pag.find('option:selected').text()
                        }
                        //针对宏部门列表控件  需要对titleValue进行处理
                        else if(item_pag.attr('data-type')=='macros'&&item_pag.attr('datafld')=='SYS_LIST_DEPT'){
                            titleValue=item_pag.find('option:selected').attr('deptname')
                        }
                        //针对宏人员列表控件  需要对titleValue进行处理
                        else if(item_pag.attr('data-type')=='macros'&&item_pag.attr('datafld')=='SYS_LIST_USER'){
                            titleValue=item_pag.find('option:selected').text()
                        }
                        //针对宏辅助角色列表控件  需要对titleValue进行处理
                        else if(item_pag.attr('data-type')=='macros'&&item_pag.attr('datafld')=='SYS_LIST_PRIV_OTHER'){
                            titleValue=item_pag.find('option:selected').text()
                        }
                        //针对宏部门主管（上级部门）列表控件  需要对titleValue进行处理
                        else if(item_pag.attr('data-type')=='macros'&&item_pag.attr('datafld')=='SYS_LIST_MANAGER2'){
                            titleValue=item_pag.find('option:selected').text()
                        }
                        //针对宏部门主管（一级部门）列表控件  需要对titleValue进行处理
                        else if(item_pag.attr('data-type')=='macros'&&item_pag.attr('datafld')=='SYS_LIST_MANAGER3'){
                            titleValue=item_pag.find('option:selected').text()
                        }
                        //该判断为部门选择控件 和 用户选择控件时，需对titleValue处理
                        else if(item_pag.attr('data-type') == 'deptselect' || item_pag.attr('data-type') == 'userselect'){
                            if(titleValue&&titleValue.indexOf('|')>-1){
                                titleValue = titleValue.split('|')[1];
                                if(titleValue.substring(titleValue.length-1,titleValue.length) == ','){
                                    titleValue = titleValue.substring(0,titleValue.length-1);
                                }
                            }
                        }
                    }

                }else{
                    if(item_title == '[当前步骤号]' || item_title == '[CUR_PRCS_ID]'){
                        titleValue = globalData.flowRunPrcs.prcsId
                    }else if(item_title == '[当前主办人姓名]' || item_title == '[CUR_USER_NAME]'){
                        titleValue = globalData.userName;
                    }else if(item_title == '[公共附件名称]' || item_title == '[ATTACH_NAME]'){
                        titleValue = '';
                        for(var j=0;j<$('#oneUploadFile .item_wordH1').length;j++){
                            if($('#oneUploadFile .item_wordH1').length ==1){
                                titleValue = GetFileNameNoExt($('#oneUploadFile .item_wordH1').eq(j).attr('title'))
                            }else{
                                titleValue += GetFileNameNoExt($('#oneUploadFile .item_wordH1').eq(j).attr('title')) + ','
                            }
                        }
                    }else if(item_title == '[公共附件个数]' || item_title == '[ATTACH_COUNT]'){
                        titleValue = $('#oneUploadFile .item_wordH1').length;
                    }else if(item_title == '[当前流程设计步骤号]' || item_title == '[CUR_FLOW_PRCS]'){
                        titleValue = globalData.flowRunPrcs.flowPrcs
                    }else if(item_title == '[当前主办人角色]' || item_title == '[CUR_USER_PRIV]'){
                        titleValue = workForm.tool.MacrosData.data.sYS_USERPRIV
                    }else if(item_title == '[当前主办人角色_辅助角色]' || item_title == '[CUR_USER_PRIV_OTHER]'){
                        var thisd = workForm.tool.MacrosData.data.sYS_USERPRIVOTHER;
                        if(thisd.substr(thisd.length-1,thisd.length) == ','){
                            thisd = thisd.substr(0,thisd.length-1);
                        }
                        titleValue = thisd;
                    }else if(item_title == '[当前主办人部门]' || item_title == '[CUR_USER_DEPT]'){
                        titleValue = workForm.tool.getMacrosData('SYS_DEPTNAME_SHORT')()
                    }else if(item_title == '[当前主办人上级部门]' || item_title == '[CUR_USER_DEPT_PARENT]'){
                        titleValue = workForm.tool.getMacrosData('SYS_MANAGER2')()
                    }else if(item_title == '[主办人会签意见]' ||　item_title == '[MAIN_USER_SIGN]'){
                        var data = globalData.sign;
                        titleValue=""
                        if(data!=''&&data!=undefined){
                            for(var j=0;j<data.length;j++){
                                if(data[j].opFlag == 1){
                                    titleValue += data[j].content
                                }
                            }
                        }
                    }else if(item_title == '[经办人会签意见]' || item_title == '[USER_SIGN]'){
                        var data = globalData.sign;
                        titleValue=""
                        if(data!=''&&data!=undefined){
                            for(var j=0;j<data.length;j++){
                                if(data[j].opFlag == 0){
                                    titleValue += data[j].content
                                }
                            }
                        }

                    }
                }
//                           判断 第二个值是字段还是类型
                if(fromDataReject[item_value]){//如果是字段并且是表单中字段的话
                    item_value = formdata[fromDataReject[item_value]];
                }else{
                    if(item_value.indexOf('[')>-1){ //如果是字段并且不是表单中字段
                        if(item_value == '[当前步骤号]' || item_value == '[CUR_PRCS_ID]'){
                            item_value = globalData.flowRunPrcs.prcsId
                        }else if(item_value == '[当前主办人姓名]' ||item_value == '[CUR_USER_NAME]'){
                            item_value = globalData.userName;
                        }else if(item_title == '[公共附件名称]'　|| item_title == '[ATTACH_NAME]'){
                            item_value = item_value;
                        }else if(item_title == '[公共附件个数]' || item_title == '[ATTACH_COUNT]'){
                            item_value = item_value;
                        }else if(item_value == '[当前流程设计步骤号]' || item_value == '[CUR_FLOW_PRCS]'){
                            item_value = globalData.flowRunPrcs.flowPrcs
                        }else if(item_value == '[当前主办人角色]' || item_value == '[CUR_USER_PRIV]'){
                            item_value = $.cookie('userPrivName')||workForm.tool.MacrosData.data.sYS_USERPRIV;
                        }else if(item_title == '[当前主办人角色_辅助角色]' || item_title == '[CUR_USER_PRIV_OTHER]'){
                            var thisd = workForm.tool.MacrosData.data.sYS_USERPRIVOTHER;
                            if(thisd.substr(thisd.length-1,thisd.length) == ','){
                                thisd = thisd.substr(0,thisd.length-1);
                            }
                            titleValue = thisd;
                        }else if(item_value == '[当前主办人部门]' || item_value == '[CUR_USER_DEPT]'){
                            item_value = workForm.tool.getMacrosData('SYS_DEPTNAME_SHORT')()
                        }else if(item_value == '[当前主办人上级部门]' ||item_value == '[CUR_USER_DEPT_PARENT]'){
                            item_value = workForm.tool.getMacrosData('SYS_MANAGER2')()
                        }else if(item_value == '[主办人会签意见]'　|| item_value == '[MAIN_USER_SIGN]'){
                            var data = globalData.sign;
                            item_value=""
                            for(var j=0;j<data.length;j++){
                                if(data[j].opFlag == 1){
                                    item_value += data[j].content
                                }
                            }
                        }else if(item_value == '[经办人会签意见]' ||item_value == '[USER_SIGN]'){
                            var data = globalData.sign;
                            item_value=""
                            for(var j=0;j<data.length;j++){
                                if(data[j].opFlag == 0){
                                    item_value += data[j].content
                                }
                            }
                        }
                    }else{ //如果是类型值的话
                        if(item_value == '数值'){
                            item_value = 'shu'
                        }else if(item_value == '日期'){
                            item_value = 'date'
                        }else if(item_value == '时间+日期'){
                            item_value = 'time';
                        }else{
                            item_value = item_value;
                        }
                    }
                }
//                           console.log(item_value)
                if(titleValue == undefined){
                    res.msg = '条件设置有误，不存在“'+item_title+'”字段，请联系系统管理员前往流程设计器修改！';
                }else{
                    //该判断为部门选择控件 且 条件为等于 时，调用judgeResult()方法来判断用户选择框和条件设置框字段是否相同（不论排序）
                    if(item_pag.attr('data-type') == 'deptselect'&&item_con=='='  ||  item_pag.attr('data-type') == 'userselect'&&item_con=='=' ){
                        check_pass=judgeResult(titleValue,item_value)
                    }
                    //该判断为部门选择控件 且 条件为不等于 时，调用judgeResult()方法来判断用户选择框和条件设置框字段是否相同（不论排序）
                    else if(item_pag.attr('data-type') == 'deptselect'&&item_con=='!=' || item_pag.attr('data-type') == 'userselect'&&item_con=='!='){
                        check_pass=!judgeResult(titleValue,item_value)
                    }
                    else{
                        check_pass = checkTileValue(titleValue,item_con,item_value);
                    }
                }
                var setitem = (i+1)
                var reg = new RegExp('\\['+setitem+'\\]',"g");//g,表示全部替换。

                prcsOutSet = prcsOutSet.replace(reg,check_pass);
            }
        });
        prcsOutSet = covertToPrcsOutSet(prcsOutSet.toLowerCase());
        if(prcsOutSet.indexOf('（') > -1 ||prcsOutSet.indexOf('）') > -1){
            prcsOutSet = prcsOutSet.replace(/\（/g, "(").replace(/\）/g, ")");
        }
        var result = eval(prcsOutSet);

        if(result == 0){
            res.flag = false;
        }
    }
    if(cb){
        cb(res);
    }
};

//判断部门选择控件 和 用户选择控件 中用户选择字段和条件设置字段是否相同(条件设置为 等于 时)
function judgeResult(titleValue,item_value) {
    var flag = 1
    if(titleValue!==undefined && item_value!==undefined){
        titleValue=titleValue.split(',')
        item_value=item_value.split(',')
    }
    if (titleValue.length !== item_value.length) {
        flag = 0
    } else {
        titleValue.forEach(function (item) {
            if (item_value.indexOf(item) === -1) {
                flag = 0
            }
        })
    }
    return flag;
}
function checkttachPriv(privNum){
    if(attachPriv.indexOf(privNum) > -1){
        return true;
    }
    return false   ;
}
var object = {};
var arrobject = [];
//初始化下拉控件
function initSelect() {
    createSelectArr();
    //初始化下拉菜单
    firstSelectArr.forEach(function(n, i){
        selectChange(n);
    });
}
//selectArr储存所有的下拉菜单
var selectArr = new Array();
//缓存顶级下拉菜单
var firstSelectArr = new Array();
var restoreFlag = false;
function createSelectArr() {
    allSelect = $("select");
    //首次循环，将下拉菜单值保存为全局变量多维数组
    allSelect.each(function(){
        var field_name = $(this).attr("name");

        selectArr[field_name] = new Array();
        $(this).children().each(function(i, e){
            selectArr[field_name][i] = e.value;
        });
    });
    //再次循环，所有的父菜单存到数组中，用于更新状态
    allSelect.each(function(i){
        //赋重写事件
        $(this).change(function(){
            selectChange($(this).attr("name"));
        });
        //判断有子菜单的
        if($(this).attr("child")) {
            var temp = $(this).attr("title");
            if(!$("select[child='"+temp+"']")[0] ) {
                firstSelectArr[i] = jQuery(this).attr("name");
            }
        }
    });
}
//处理关联菜单的子菜单选项,传入：关联菜单
function selectChange(Select) {
    var SelectObj = $("select[name='"+Select+"']");
    var parent_str = "|"+$(SelectObj).val();
    if($(SelectObj).attr("child") != undefined) {
        //子对象
        var childObj = $("select[title='"+$(SelectObj).attr("child")+"']");
        if(childObj.length == 0){return false;}
        //记录原始数据，重写option后用此值恢复
        var childVal = $(childObj).val();
        //先删除所有option
        childObj.children().remove();
        //循环添加option
        selectArr[$(childObj).attr("name")].forEach(function(n, i){
            if(restoreFlag){
                if(parent_str!='|' && n.indexOf(parent_str) != -1)
                {
                    var val_arr = n.split("|");
                    $(childObj).append("<option value='"+n+"'>"+val_arr[0]+"</option>");
                }
            }else{
                var val_arr = n.split("|");
                $(childObj).append("<option value='"+n+"'>"+val_arr[0]+"</option>");
            }
        });
        childObj.val(childVal);
        selectChange($(childObj).attr("name"));
    }
    else {
        return;
    }
}
$(function () {
    layer.load();
    var history = document.referrer;
    var savebtn = false;
    globalData.flowId = $.getQueryString("flowId");
    globalData.flowStep = $.getQueryString("flowStep") || '';
    globalData.prcsId = $.getQueryString("prcsId") || '';
    globalData.runId = $.getQueryString("runId") || '';
    globalData.tableName = $.getQueryString("tableName") || '';
    globalData.tabId =  $.getQueryString("tabId") || '';

    if(window.location.href.indexOf('&runname=') > -1){
       var runnames = window.location.href.split('&runname=')[1].split('&lang=')[0];
        globalData.runname = decodeURIComponent(runnames.replace(/\+/g,'%20'));


    }else{
        globalData.runname = '';
    }
    var gobackIndex = 0;
    var workformh5 = {
        /************移动端工作流的初始化方法************************/
        init:function (cb) {
            var _this = this;
            workForm.init({
                    formhtmlurl:'../../workflow/work/workfastAdd',//URL
                    resdata:{
                        flowId:globalData.flowId,
                        runId:globalData.runId=='no'?'':globalData.runId,
                        prcsId:globalData.prcsId,
                        flowStep:globalData.flowStep,
                        tableName:globalData.tableName,
                        tabId:globalData.tabId
                    },
                    flowStep:globalData.prcsId,//预览
                    ish5:true,
                    target:'.cont_form',
                    beforeToken:beforeToken
                }, function (data,option,target) {
                    var obj = data.object;
                    globalData.flowRun = obj.flowRun;
					globalData.flowFormType = obj.flowFormType;
					globalData.listFp = obj.listFp;
                    globalData.flowRunPrcs = obj.flowRunPrcs;
                    globalData.option = option;
                    globalData.flowTypeModel = obj.flowTypeModel;
                    globalData.attachPriv = obj.attachPriv;
                    globalData.allowBack = obj.allowBack;
                    globalData.flowPrcs = obj.flowRunPrcs.flowPrcs;
                    flowPrcs =  data.object.flowRunPrcs.flowPrcs;
                    globalData.signlock = obj.signlock;
                    globalData.conditionDesc = obj.conditionDesc;
                    globalData.prcsOut = obj.prcsOut;
                    globalData.flowProcesses = obj.flowProcesses;
                    globalData.prcsType = obj.flowProcesses.prcsType;
                    globalData.prcsOutSet = obj.prcsOutSet;
                    attachPriv = obj.attachPriv;
                    globalData.gatherNodePriv = obj.gatherNodePriv;
                    feedback = obj.feedback;
                    globalData.opflag = obj.flowRunPrcs.opFlag||'';
                    globalData.feedback = obj.feedback;
                    globalData.checkTurnPriv = obj.checkTurnPriv;

                    $('#step').val('第'+globalData.flowStep+'步：'+obj.flowProcesses.prcsName);
                    if(feedback == '1'){
                        $('#signText').attr("disabled","disabled").addClass('grey');
                        $('.sign_btn').hide();
                    }
                    if(globalData.signlock == 1){
                        $('.gapp_textarea').attr("disabled",true);
                    }
                    if(checkttachPriv(1)){
                        $('.xzbtn').show();
                    }else{
                        $('.xzbtn').hide();
                    }
                    var runid = data.object.flowRun.runId;
                    if(globalData.flowStep != '1'&&globalData.opflag == '1'){
                        if(obj.flowRunPrcs.otherUser == undefined||obj.flowRunPrcs.otherUser.trim() == ""){
                            $('#weituo').show();
                        }
                    }



                    /*********************工作交办按钮显示方法*************************/
                    if (globalData.flowProcesses && globalData.flowProcesses.operationButton && globalData.flowProcesses.operationButton.indexOf('8') > -1) {
                        $.ajax({
                            type: 'GET',
                            url: '/operation/selFlowOperationById?opId=8',
                            async: false,
                            success: function(res) {
                                if (res.flag) {
                                    $('#assignment').show();
                                }
                            }
                        });
                    }

                    /*********************交办详情按钮显示方法*************************/
                    $.get('/flowAssign/query', {runId: globalData.flowRun.runId}, function(res){
                        if (res.flag) {
                            $('#assignmentDetail').show();
                        }
                    });

                    /*********************判断是否显示相关流程(父子流程和关联流程)*************************/
                    $.get('/workflow/work/prentAndSonFlow', {runId: globalData.flowRun.runId}, function (json) {
                        var parentRunId = '';
                        if (json.flag) {
                            var str2 = '';
                            if (json.object) {
                                parentRunId = json.object.runId;
                                str2 += '<tr><td>父流程</td><td><a flowid="' + json.object.flowId + '" runid="' + json.object.runId + '" href="javascript:;" style="color: blue;" class="open_flow_work">' + json.object.runName + '</a></td></tr>';
                            }
                            if (json.obj.length != 0) {
                                json.obj.forEach(function(item){
                                    str2 += '<tr><td>子流程</td><td><a flowid="' + item.flowId + '" runid="' + item.runId + '" href="javascript:;" style="color: blue;" class="open_flow_work">' + item.runName + '</a></td></tr>';
                                })
                            }
                            $('.connect_work_table').append(str2);
                            if (str2 != '') {
                                $('.connect_work').show();
                            }
                        }
                        // 获取关联流程数据
                        $.get('/flowRun/findrelationRunIds', {runId: globalData.flowRun.runId+','+parentRunId}, function (res) {
                            if (res.flag && res.obj.length > 0) {
                                var str = '';
                                res.obj.forEach(function (item) {
                                    str += '<tr><td>关联流程</td><td><a flowid="' + item.flowId + '" runid="' + item.runId + '" href="javascript:;" style="color: blue;" class="open_flow_work">' + item.runName + '</a></td></tr>';
                                });
                                $('.connect_work_table').append(str);
                                $('.connect_work').show();
                            }
                        });
                    });
                    /************回退按钮显示方法************************/
                    if(globalData.allowBack != 0){
                       $('#backBtn').show();
                    }
                    /************删除按钮隐藏方法************************/
                    if(globalData.flowStep !=1){
                        $('#deleteBtn').hide();
                    }
                    /************调用移动端回退的方法************************/
                    $('#backBtn').click(function () {
                        gobackIndex = 1;
                        _this.saveFlowData(function(res){
                            if(res.flag){
                                //alert("保存成功");
                                if($.getQueryString("type") != 'EWC'){
                                    window.location.href='feedback?flowId='+globalData.flowId+'&flowStep='+globalData.flowStep+'&prcsId='+globalData.prcsId+'&runId='+globalData.flowRun.runId+'&allowback='+globalData.allowBack+'&tableName='+globalData.tableName+'&tabId='+globalData.tabId+'&frpId='+globalData.flowRunPrcs.id;
                                    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                        try{
                                            window.webkit.messageHandlers.rightTitle.postMessage({'title':'转交','name':'回退','function':'feedback'});
                                        }catch(err){
                                            rightTitle('转交','回退','feedback');
                                        }
                                    } else if (/(Android)/i.test(navigator.userAgent)) {
                                        Android.rightTitle('转交','回退','feedback');
                                    }
                                }else{
                                    window.location.href='feedback?flowId='+globalData.flowId+'&flowStep='+globalData.flowStep+'&prcsId='+globalData.prcsId+'&runId='+globalData.flowRun.runId+'&allowback='+globalData.allowBack+'&tableName='+globalData.tableName+'&tabId='+globalData.tabId+'&type=EWC';
                                }

                                layer.closeAll();
                            }else{
                                $.layerMsg({content:"保存失败！",icon:2},function(){
                                    layer.closeAll();
                                });
                            }

                        });
                    });

                    /************调用移动端查看原始表单的方法************************/
                    $('#formInfo').click(function () {
                    gobackIndex = 1;
                    _this.saveFlowData(function(res){
                        if(res.flag){
                            $.layerMsg({content:"保存成功！",icon:1},function(){

                            });
                            formInfo();
                        }else{
                            $.layerMsg({content:"保存失败！",icon:2},function(){

                            });
                        }
                        layer.closeAll();
                    });
                });
                    /************和后台获取附件信息的方法************************/
                    $.ajax({
                        type: "get",
                        url: "findworkUpload",
                        dataType: 'JSON',
                        data: {
                            runId:runid
                        },
                        beforeSend : function(request) {
                            if(beforeToken != ''){
                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                            }
                        },
                        success: function (obj) {
                            var data = obj.obj;
                            var img = '';
                            var names = '';
                            for(var i=0;i<obj.obj.length;i++){
                                var pic_name = obj.obj[i].attachName;
                                var index = pic_name .lastIndexOf("\.");
                                var pic_name = pic_name.substring(index + 1, pic_name .length);
                                var http = 'http://'+ window.location.host;
                                if(pic_name == "png"||pic_name == "jpeg"||pic_name == "bmp"||pic_name == "jpg"){
                                    img += '<a style="display: none" href="/xs?'+ obj.obj[i].attUrl +'">下载</a><img id="blah" src="/xs?'+ obj.obj[i].attUrl +'" onclick="anios($(this))" style="width:50px;height:50px;margin-right: 10px;margin-bottom: 10px;" url="'+ http + '/xs?'+ obj.obj[i].attUrl +'" name="'+ obj.obj[i].attachName +'">';
                                }else{
                                    if($.getQueryString("type") == 'EWC'){
                                        names += '<p><a style="margin-bottom: 5px;color: #095de0;" href="'+ http + '/download?'+ obj.obj[i].attUrl +'">'+ obj.obj[i].attachName +'</a></p>'
                                    }else {
                                        names += '<p url="'+ http + '/download?'+ obj.obj[i].attUrl +'" name="'+ obj.obj[i].attachName +'" onclick="anios($(this))">'+ obj.obj[i].attachName +'</p>'
                                    }
                                }

                            }
                            $('.photo_box').append(img);
                            $('.uploadbox').append(names);
                        }
                    });
                    /************和后台获取会签信息的方法************************/
                    $.ajax({
                        type: "get",
                        url: "findworkfeedback",
                        dataType: 'JSON',
                        data: {
                            prcsId:globalData.flowStep,
                            signlock: globalData.signlock,
                            flowPrcs:globalData.flowPrcs,
                            runId:runid
                        },
                        beforeSend : function(request) {
                            if(beforeToken != ''){
                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                            }
                        },
                        success: function (obj) {
                                globalData.data = obj.obj;
                                // 如果禁止会签，已有会签意见则显示意见隐藏输入框，如果没有会签意见则隐藏会签意见区
                                if (feedback == '1') {
                                    if (obj.obj.length > 0) {
                                        $('#signText').hide()
                                    } else {
                                        $('#signModule').hide()
                                    }
                                }

                                var str = '';
                                for(var i=0;i<obj.obj.length;i++){
                                    if(obj.obj[i].feedFlag == 2){
                                        var feedflagstr = '<span style="font-size: 15px;font-weight: bold;color: red;">（回退意见）：</span>';
                                    }else{
                                        var feedflagstr = '：';
                                    }
                                    str +=  '<div style="text-align: left;margin: 0px auto;margin-top: 15px;width: 90%;">' +
                                        '<span style="margin-bottom: 5px;font-size: 15px;font-weight: bold;">'+obj.obj[i].users.userName+feedflagstr+'</span>' +
                                        '<span style="font-size: 14px;padding: 0 5px;">'+obj.obj[i].content+'</span>' +
                                        '<span style="margin-bottom: 5px;font-size: 14px;">('+obj.obj[i].editTime+')</span>' +
                                        '</div>'
                                }
                                $('.hqbox').html(str);

                        }
                    });
                    if(globalData.runname != ''){
                        var datarunname = globalData.runname;
                    }else{
                        var datarunname = data.object.flowRun.runName;
                    }
                    $('#flowName').text(datarunname);
                    $('#flowBeginUser').text(data.object.flowRun.userName);
                    $('#flowBeginTime').text(data.object.flowRun.beginTime);
                    $('#flowRunId').text('No.'+data.object.flowRun.runId);
                    $('#deleteBtn').attr('tid',globalData.flowRunPrcs.id);
                    if(target.prop('outerHTML').indexOf('splitBox') > -1){
                        globalData['split'] = 1;
                    }
                    _this.buildBody(target);
                    _this.buildEvent();
                    $('body').append('<script src="/js/workflow/plugin/countersignature/main.js"></script>');
                    cb();
                    /*************处理radio类型input在disabled下无法修改样式的问题 通过将已选中的radio 去除掉disabled解决 仅限于工作流-办理页面******************/
                    var length = $('input[type=radio]').length;
                    if(length != 0){
                        for(var i=0;i<length;i++){
                            if($('input[type=radio]').eq(i).attr('checked') == 'checked'){
                                $('input[type=radio]').eq(i).removeAttr('disabled');
                            }
                        }
                    }

                    if($('select[data-type=select]').length != 0){
                        restoreFlag = true;
                        initSelect();
                        $("option").each(function(index){
                            var text_index=$(this).text().indexOf("|");
                            if(text_index > 0) {
                                $(this).text($(this).text().substring(0,text_index));
                            }
                        });
                    }
                    /*************处理选日期控件***********************************************************/
                    var length = $('input[data-type=calendar]').length;
                    if(length != 0&&$.getQueryString("type") == 'EWC'){
                        for(var i=0;i<length;i++){
                            if(!$('input[data-type=calendar]').eq(i).is(':disabled')){
                                if($('input[data-type=calendar]').eq(i).attr('dates_format').indexOf('hh:mm:ss') > -1){
                                    new Jdate({
                                        el: '#'+ $('input[data-type=calendar]').eq(i).attr('id'),
                                        format: 'YYYY-MM-DD hh:mm:ss',
                                        beginYear: 2000,
                                        endYear: 2100
                                    })
                                }else{
                                    new Jdate({
                                        el: '#'+ $('input[data-type=calendar]').eq(i).attr('id'),
                                        format: 'YYYY-MM-DD',
                                        beginYear: 2000,
                                        endYear: 2100
                                    })
                                }
                            }
                        }
                    }
                    if(globalData.split == 1){
                        var firstPrcsItem = globalData.flowProcesses.prcsItem.split(',')[0];
                        if(globalData.flowProcesses.prcsItem.split(',')[0] == '[A@]'){
                            firstPrcsItem = globalData.flowProcesses.prcsItem.split(',')[1];
                        }
                        var firstPrcsItemNum = $('.form_item[title='+ firstPrcsItem +']').parents('tr').prev().find('td').eq(1);
                        firstPrcsItemNum.append('<a name="aa"></a><a href="#aa"></a>');
                        location.href = "#aa";window.location.hash = "#aa";
                    }
                    /*************声明下评分控件START******************************************************/
                    if($('.mark').length != 0){
                        for(var i=0;i<$('.mark').length;i++){
                            var disabled = $('.mark .form_item').eq(i).attr('disabled');
                            var formItemId = $('.mark .form_item').eq(i).attr('name');
                            var value = $('.mark .form_item').eq(i).val();
                            scoreFun($("#startone"+formItemId));
                            if(value != '-1'){
                                $("#startone"+formItemId).find('a').eq(value).addClass('clibg');
                            }
                            if(disabled == 'disabled'){
                                $('.mark .form_item').eq(i).parent().find('a').prop("onclick",null).off("click");
                                $('head').append('<style>#startone'+ formItemId +' .star_score a:hover {\n' +
                                    '        background: none;\n' +
                                    '    }</style>')
                            }

                        }
                    }
                    /***************判断是否显示添加经办人*****************/
                    if(globalData.flowProcesses && globalData.flowProcesses.countersign == 1){
                        if (globalData.flowRunPrcs.opaddUser == undefined || globalData.flowRunPrcs.opaddUser == ''){
                            $('#addSign').show();
                        }else{
                            if (globalData.flowProcesses.countersignAgain == '1'){
                                $('#addSign').show();
                            }
                        }
                    }else{
                        if (globalData.flowRunPrcs.opaddUser !=undefined && globalData.flowRunPrcs.opaddUser !='' && globalData.flowProcesses.countersignAgain == '1'){
                            $('#addSign').show();
                        }
                    }

            });

        },
        /************调用工作流转交按钮的方法************************/
        turnH5Btn: function () {
            var _this = this;
            //查看当前流程是否已办结
            $.ajax({
                url: '/workflow/work/selectFind',
                type: 'GET',
                data: {
                    flowId: $.GetRequest().flowId,
                    prcsId: $.GetRequest().flowStep,
                    flowPrcs: $.GetRequest().prcsId,
                    runId: $.GetRequest().runId
                },
                success: function (res) {
                    if (res.flag && res.object == 'err') {
                        layer.msg('当前流程已办结', {time: 1000}, function () {
                            if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                try{
                                    window.webkit.messageHandlers.finishWork.postMessage({});
                                }catch(err){
                                    finishWork();
                                }
                            } else if (/(Android)/i.test(navigator.userAgent)) {
                                Android.finishWebActivity();
                            } else {
                                var href = location.href.replace('workformh5', 'workformh5PreView');
                                location.href = href;
                            }
                        });
                    } else {
                        if (globalData.checkTurnPriv == 0) {
                            layer.msg('经办人未办理完毕，无法转交');
                            return false;
                        }
                        var feedbackflag = false;
                        var NewuserId = userId;
                        globalData.data.forEach(function(v,i){
                            if(v.userId == NewuserId&&$.GetRequest().prcsId == v.flowPrcs){
                                feedbackflag = true;
                            }
                        })
                        if(globalData.feedback == '2'){
                            if($('#signText').val() ==""&&!feedbackflag){
                                $.layerMsg({content:'请提交会签意见',icon:6});
                                return false;
                            }
                        }
                        if (globalData.gatherNodePriv == 1) {
                            layer.msg(qzhb);
                        } else {
                            _this.saveFlowData(function (res) {
                                if (res.flag) {
                                    var content = $('.signBox .gapp_textarea').val();
                                    if (content == "") {
                                        if ($.getQueryString("type") == 'EWC') {
                                            var type = '&type=EWC';
                                        } else {
                                            var type = '';
                                        }
                                        window.location.href = 'turnh5?flowId=' + globalData.flowId + '&flowStep=' + globalData.flowStep + '&prcsId=' + globalData.prcsId + '&runId=' + globalData.flowRun.runId + '&tableName=' + globalData.tableName + '&tabId=' + globalData.tabId + type;
                                    } else {
                                        $.ajax({
                                            type: "get",
                                            url: "../../workflow/work/workfeedback",
                                            dataType: 'JSON',
                                            data: {
                                                prcsId: globalData.prcsId,
                                                runId: globalData.flowRun.runId,
                                                flowPrcs: globalData.flowPrcs,
                                                content: content,
                                                file: '',
                                                feedFlag: '0'
                                            },
                                            beforeSend: function (request) {
                                                if (beforeToken != '') {
                                                    request.setRequestHeader("Authorization", 'Bearer ' + beforeToken);
                                                }
                                            },
                                            success: function (res) {
                                                $('.signBox .gapp_textarea').val('');
                                            }
                                        })
                                    }
                                    if ($.getQueryString("type") == 'EWC') {
                                        window.location.href = 'turnh5?flowId=' + globalData.flowId + '&flowStep=' + globalData.flowStep + '&prcsId=' + globalData.prcsId + '&runId=' + globalData.flowRun.runId + '&tableName=' + globalData.tableName + '&tabId=' + globalData.tabId + '&type=EWC';
                                    } else {
                                        window.location.href = 'turnh5?flowId=' + globalData.flowId + '&flowStep=' + globalData.flowStep + '&prcsId=' + globalData.prcsId + '&runId=' + globalData.flowRun.runId + '&tableName=' + globalData.tableName + '&tabId=' + globalData.tabId;
                                        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                            try{
                                                window.webkit.messageHandlers.rightTitle.postMessage({'title':'转交','name':'321','function':'turn'});
                                            }catch(err){
                                                rightTitle('转交','321','turn');
                                            }
                                        } else if (/(Android)/i.test(navigator.userAgent)) {
                                            //alert(navigator.userAgent);
                                            Android.rightTitle('转交', '123', 'turn');
                                        }
                                    }

                                }
                                layer.closeAll();
                            });
                        }
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        },
        buildEvent:function () {
            /************************子流程点击跳转************************/
            $(document).on('click','.child_flow', function(){
                var url = $(this).data('url');
                if($.getQueryString("type") == 'EWC'){
                    window.location.href = url + '&formInfo=formInfo';
                }else{
                    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                        try{
                            window.webkit.messageHandlers.formInfoUrlLink.postMessage({'url':url + '&formInfo=formInfo','name':'原始表单'});
                        }
                        catch(err) {
                            formInfoUrlLink(url + '&formInfo=formInfo','原始表单');
                        }
                    } else if (/(Android)/i.test(navigator.userAgent)) {
                        Android.formInfoUrlLink(url+ '&formInfo=formInfo','原始表单');
                    }
                }
            });
            /*************移动端工作流控件排序功能**************************************************/
            $.ajax({
                type: "get",
                url: "/form/getMobileDataSort",
                dataType: 'JSON',
                data: {
                    formId: globalData.flowFormType.formId
                },
                beforeSend : function(request) {
                    if(beforeToken != ''){
                        request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                    }
                },
                async:false,
                success: function(res) {
                    var formData = workForm.option.dataName || {};
                    var prcsItem = workForm.option.prcsItem || '';
                    if(res.flag){
                        var arr = res.obj.split(',');
                        var str = '';
                        var strArr = [];
                        var arrObj = {};
                        arr.forEach(function(v,i){
                            var name = v.split('|')[0] || '';
                            var isShow = v.split('|')[1] == 0 ? false : true;
                            arrObj[name] = isShow;
                            if(name&&name.indexOf('DATA_')>-1){
                                object[name] = true;
                                if($('[name='+ name +']').parents('tr').prop("outerHTML")){
                                    // var dis = $('[name='+ name +']').attr('disabled');
                                    var title = $('[name=' + name + ']').attr('title');
                                    var dataType = $('[name=' + name + ']').attr('data-type');
                                    // 判断是否为可写字段
                                    if (prcsItem.indexOf(title) == -1) { // 不可写
                                        // 判断是否配置app显示
                                        if (!isShow) { // 未配置
                                            $('[name=' + name + ']').parents('tr').hide()
                                        } else { // 已配置
                                            if (!formData[name]) {
                                                $('[name=' + name + ']').parents('tr').hide()
                                            } else if (dataType == 'checkbox' && formData[name] == '0') {
                                                $('[name=' + name + ']').parents('tr').hide()
                                            }
                                        }
                                    }
                                    // str += $('[name='+ name +']').parents('tr').prop("outerHTML");
                                    strArr.push($('[name='+ name +']').parents('tr'));
                                }
                            }
                        });
                        arrobject.forEach(function(v,i){
                            if(v&&v.indexOf('DATA_')>-1){
                                if(!object[v]){
                                    if ($('[name=' + v + ']').parents('tr').prop("outerHTML")) {
                                        // var dis = $('[name=' + v + ']').attr('disabled');
                                        var title = $('[name=' + v + ']').attr('title');
                                        var dataType = $('[name=' + v + ']').attr('data-type');
                                        // 判断是否为可写字段
                                        if (prcsItem.indexOf(title) == -1) { // 不可写
                                            // 判断是否配置app显示
                                            if (!arrObj[v]) { // 未配置
                                                $('[name=' + v + ']').parents('tr').hide()
                                            } else { // 已配置
                                                if (!formData[v]) {
                                                    $('[name=' + v + ']').parents('tr').hide()
                                                } else if (dataType == 'checkbox' && formData[v] == '0') {
                                                    $('[name=' + v + ']').parents('tr').hide()
                                                }
                                            }
                                        }
                                        // str += $('[name='+ v +']').parents('tr').prop("outerHTML");
                                        strArr.push($('[name=' + v + ']').parents('tr'));
                                    }
                                }
                            }
                        });
                        $('#content tbody').empty();
                        $('#content tbody').html(strArr);
                    }else{
                        arrobject.forEach(function (v, i) {
                            if (v && v.indexOf('DATA_') > -1) {
                                if ($('[name=' + v + ']').parents('tr').prop("outerHTML")) {
                                    // var dis = $('[name=' + v + ']').attr('disabled');
                                    var title = $('[name=' + v + ']').attr('title');
                                    var dataType = $('[name=' + v + ']').attr('data-type');
                                    // 判断是否为可写字段
                                    if (prcsItem.indexOf(title) == -1) { // 不可写
                                        if (!formData[v]) { // 判断内容是否为空，为空不显示
                                            $('[name=' + v + ']').parents('tr').hide()
                                        } else if (dataType == 'checkbox' && formData[v] == '0') {
                                            $('[name=' + v + ']').parents('tr').hide()
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
            });

            /*************声明下下拉框控件START联动功能*********************************************/
            var _this = this;
            $('#turnBtn').click(function () {
                _this.turnH5Btn();
            });
            $('.deptselecth5').click(function () {
                dept_id = $(this).attr('id');
                layer.open({
                    type: 2,
                    shade:true,
                    area: ['360px', '500px'],
                    content: ['/common/selectDept', 'no']
                });

            });
            $('.userselecth5').click(function () {
                user_id = $(this).attr('id');
                if($(this).attr('selectId') == '1'){
                    var num = '?0';
                }else{
                    var num = '';
                }
                layer.open({
                    type: 2,
                    shade:true,
                    area: ['98%', '500px'],
                    content: ['/common/selectUser'+num, 'no']
                });

            });
            //加载列表控件事件
            $('.btn_list').click(function () {
                $('#listcontent').html( $(this).parent().find('table'));
                $('#listcontent').find('table').show();
                var lv_size = $('#listcontent').find('table').attr('lv_size');
                $('#listbox').show();
            });
            //
            $('#list_btn_close').click(function () {
                var tableObj = $('#listcontent').find('table');
                tableObj.hide();
                var id = tableObj.attr('id');
                $('#content #'+id).before( tableObj);
                $('#listbox').hide();
                calcutarget($('.amount'))
            });
            $('#lctbtn').click(function () {
                if($.getQueryString("type") == 'EWC'){
                    window.location.href = "/flowSetting/processDesignToolTwo?flowId="+ globalData.flowId +"&rilwId="+ globalData.runId;
                }else{
                    if(/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                        try{
                            window.webkit.messageHandlers.lookFlowChart.postMessage({'url':"/flowSetting/processDesignToolTwo?flowId="+ globalData.flowId +"&rilwId="+ globalData.runId});
                        }catch(err){
                            lookFlowChart("/flowSetting/processDesignToolTwo?flowId="+ globalData.flowId +"&rilwId="+ globalData.runId);
                        }
                    }else if(/(Android)/i.test(navigator.userAgent)){
                        Android.lookFlowChart("/flowSetting/processDesignToolTwo?flowId="+ globalData.flowId +"&rilwId="+ globalData.runId);
                    }
                }
            });
            /************工作流 保存 按钮 点击方法************************/
            $('#saveBtn').click(function (){
                savebtn = true;
                _this.saveFlowData(function(res){
                    if(res.flag){
                        var content = $('.signBox .gapp_textarea').val();
                        if(content != ""){
                            $.ajax({
                                type: "get",
                                url: "../../workflow/work/workfeedback",
                                dataType: 'JSON',
                                data: {
                                    prcsId:globalData.prcsId,
                                    runId:globalData.flowRun.runId,
                                    flowPrcs:globalData.flowPrcs,
                                    content:content,
                                    file:'',
                                    feedFlag:'0'
                                },
                                beforeSend : function(request) {
                                    if(beforeToken != ''){
                                        request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                                    }
                                },
                                success: function(res){

                                }
                            })
                        }
                        $.layerMsg({content:"保存成功！",icon:1},function(){

                        });
                        if($.getQueryString("type") == 'EWC'){
                            window.history.go(-1);
                        }else{
                            /************调用移动端返回工作流列表方法************************/
                            if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                try{
                                    window.webkit.messageHandlers.finishWork.postMessage({});
                                }catch(err){
                                    finishWork();
                                }
                            } else if (/(Android)/i.test(navigator.userAgent)) {
                                Android.finishWebActivity();
                            }
                        }

                    }else{
                        $.layerMsg({content:"保存失败！",icon:2},function(){

                        });
                    }
                    setTimeout(function () {
                        layer.closeAll();
                    },1000)

                },'noCheck');
            });

            /************会签功能调用办理完毕btn************************/
            $('#opflagturn').click(function(){
                var feedbackflag = false;
                globalData.data.forEach(function(v,i){
                    if(v.userId == userId&&$.GetRequest().prcsId == v.flowPrcs){
                        feedbackflag = true;
                    }
                })

                if(globalData.feedback == '2'){
                    if($('#signText').val() ==""&&!feedbackflag){
                        $.layerMsg({content:'请提交会签意见',icon:6});
                        return false;
                    }
                }
                var loadingIndex = layer.load();
                //判断会签意见控件是否必填
                var form_item=$('#content .form_item');
                for(var i=0; i<form_item.length;i++){
                    var obj = form_item.eq(i);
                    var datatype = obj.attr("data-type");
                    var ismust = obj.attr('ismust');
                    var isMustValue
                    var isCheck = true;
                    if(datatype == 'sign'){
                        isMustValue = '';
                        // 获取输入框的值
                        var valueSign = obj.val().trim();
                        // 有值跳过
                        if(valueSign){
                            isMustValue = valueSign;
                        }else{ // 无值，需要判断当前用户当前步骤是否填写过意见
                            var pre = obj.prev();
                            var $eiderarea = pre.find('.eiderarea');
                            var flowRunPrcs = workForm.option.flowRunPrcs;
                            $eiderarea.each(function(index, ele){
                                if ($(this).attr('user_id') == flowRunPrcs.userId && $(this).attr('prcs_id') == flowRunPrcs.flowPrcs) {
                                    var signHtml = $(ele).prop("outerHTML");
                                    var contentArr = signHtml.split(/>/);
                                    var content = contentArr[1].split(/</)[0];
                                    // var content = signHtml.match(/>(\S*?)<br>/)[1];
                                    if (content.indexOf('{{content}}') == -1 && content.trim() != '') {
                                        isMustValue += content
                                    }
                                }
                            });
                        }
                    }
                    if(isCheck && ismust == 'true' && isMustValue == ""){          //适用于设置了当前流程必填字段和当前流程转出条件的流程
                        if(gobackIndex != 1){                      //适用于设置了当前流程必填字段和当前流程转出条件的流程，点击回退按钮兼容效果
                            // flag = true;
                            layer.close(loadingIndex);
                            layer.msg('请填写'+obj.attr('title'), {icon: 1});
                            return false;
                        }
                    }
                }
                var flowfun = globalData.flowRun;
                var form_item=$('.special_form_item');
                var sign=$('.sign');
                /********会签控件开始**********/
                if(sign.length != 0){
                    var signdata = [];
                    for(var i=0;i<sign.length;i++){
                        if(!sign.eq(i).attr('disabled')){
                            var pre = sign.eq(i).prev();
                            var realValue = sign.eq(i).val().trim();
                            var baseData = {};
                            var value = '';
                            if (realValue) {
                                value = Mustache.render(pre.find('.eiderarea').eq(pre.find('.eiderarea').length-1).prop("outerHTML"),{content:''});
                            }
                            baseData["key"] = sign.eq(i).attr('name');
                            baseData["value"]=value;
                            signdata.push(baseData);
                        }
                    }
                    if(signdata.length != 0){
                        $.ajax({
                            type: "post",
                            url: "/workflow/work/signControl",
                            dataType: 'JSON',
                            data: {
                                runId:flowfun.runId,
                                flowId:globalData.flowId,
                                signdata:JSON.stringify(signdata)
                            },
                            beforeSend : function(request) {
                                if(beforeToken != ''){
                                    request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                                }
                            },
                            async:false,
                            success: function(res){}
                        });
                    }
                }
                /********传阅意见控件开始**********/
                if(form_item.length != 0){
                    for(var i=0;i<form_item.length;i++){
                        var obj = form_item.eq(i);
                        var ismust = obj.attr('ismust');

                        if(ismust == 'true'&&$('.countersignature_itemhide').length == 0){          //适用于设置了当前流程必填字段和当前流程转出条件的流程
                            layer.close(loadingIndex);
                            $.layerMsg({content: '请签名!', icon: 1});
                            return false;
                        }else{
                            saveCSNtr_item(obj,function(){
                                if(form_item.length-1 == i){
                                    var finishdata={
                                        runId:flowfun.runId,
                                        prcsId : globalData.flowStep,
                                        flowPrcs : globalData.flowPrcs,
                                        flowId:globalData.flowId,
                                        tableName:globalData.tableName,
                                        tabId:globalData.tabId,
                                    };
                                    $.ajax({
                                        type: "post",
                                        url: "/workflow/work/saveHandle",
                                        dataType: 'JSON',
                                        data: finishdata,
                                        beforeSend : function(request) {
                                            if(beforeToken != ''){
                                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                                            }
                                        },
                                        success: function(res){

                                            if(res.flag){
                                                // 保存会签意见
                                                finishdata.content = $('#signText').val();
                                                finishdata.feedFlag = '0';
                                                finishdata.file = '';
                                                // 判断会签意见填写是否为空
                                                // 如果不为空  则保存会签意见
                                                // 如果为空    跳过保存会签意见 提示流程办理完毕保存成功
                                                if(finishdata.content!=''){
                                                    $.ajax({
                                                        type:"get",
                                                        url:"/workflow/work/workfeedback",
                                                        dataType:"json",
                                                        data:finishdata,
                                                        beforeSend : function(request) {
                                                            if(beforeToken != ''){
                                                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                                                            }
                                                        },
                                                        success:function (res) {
                                                            layer.close(loadingIndex);
                                                            if(res.flag){
                                                                $.layerMsg({content:'保存成功！',icon:1},function(){

                                                                });
                                                                /************调用移动端返回工作流列表方法************************/
                                                                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                                                    try{
                                                                        window.webkit.messageHandlers.finishWork.postMessage({});
                                                                    }catch(err){
                                                                        finishWork();
                                                                    }
                                                                } else if (/(Android)/i.test(navigator.userAgent)) {
                                                                    Android.finishWebActivity();
                                                                }
                                                            }
                                                        }
                                                    })
                                                }else{
                                                    layer.close(loadingIndex);
                                                    $.layerMsg({content:'保存成功！',icon:1},function(){

                                                    });
                                                    /************调用移动端返回工作流列表方法************************/
                                                    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                                        try{
                                                            window.webkit.messageHandlers.finishWork.postMessage({});
                                                        }catch(err){
                                                            finishWork();
                                                        }
                                                    } else if (/(Android)/i.test(navigator.userAgent)) {
                                                        Android.finishWebActivity();
                                                    }
                                                }

                                            }else{
                                                layer.close(loadingIndex);
                                                $.layerMsg({content:"保存失败！",icon:2},function(){

                                                });
                                            }
                                        }
                                    });
                                }

                            });
                        }
                    }

                }else{
                    var finishdata={
                        runId:flowfun.runId,
                        prcsId : globalData.flowStep,
                        flowPrcs : globalData.flowPrcs,
                        flowId:globalData.flowId,
                        tableName:globalData.tableName,
                        tabId:globalData.tabId,
                    };
                    $.ajax({
                        type: "post",
                        url: "/workflow/work/saveHandle",
                        dataType: 'JSON',
                        data: finishdata,
                        beforeSend : function(request) {
                            if(beforeToken != ''){
                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                            }
                        },
                        success: function(res){
                            if(res.flag){
                                // 保存会签意见
                                finishdata.content = $('#signText').val();
                                finishdata.feedFlag = '0';
                                finishdata.file = '';
                                // 判断会签意见填写是否为空
                                // 如果不为空  则保存会签意见
                                // 如果为空    跳过保存会签意见 提示流程办理完毕保存成功
                                if(finishdata.content!=''){
                                    $.ajax({
                                        type:"get",
                                        url:"/workflow/work/workfeedback",
                                        dataType:"json",
                                        data:finishdata,
                                        beforeSend : function(request) {
                                            if(beforeToken != ''){
                                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                                            }
                                        },
                                        success:function (res) {
                                            layer.close(loadingIndex);
                                            if(res.flag){
                                                $.layerMsg({content:'保存成功！',icon:1},function(){

                                                });
                                                /************调用移动端返回工作流列表方法************************/
                                                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                                    try{
                                                        window.webkit.messageHandlers.finishWork.postMessage({});
                                                    }catch(err){
                                                        finishWork();
                                                    }
                                                } else if (/(Android)/i.test(navigator.userAgent)) {
                                                    Android.finishWebActivity();
                                                }
                                            }
                                        }
                                    })
                                }else{
                                    layer.close(loadingIndex);
                                    $.layerMsg({content:'保存成功！',icon:1},function(){

                                    });
                                    /************调用移动端返回工作流列表方法************************/
                                    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                        try{
                                            window.webkit.messageHandlers.finishWork.postMessage({});
                                        }catch(err){
                                            finishWork();
                                        }
                                    } else if (/(Android)/i.test(navigator.userAgent)) {
                                        Android.finishWebActivity();
                                    }
                                }

                            }else{
                                layer.close(loadingIndex);
                                $.layerMsg({content:"保存失败！",icon:2},function(){

                                });
                            }
                        }
                    });
                }


            });
            /************工作流 删除 按钮 点击方法************************/
            $('#deleteBtn').click(function () {
                var tid=$(this).attr('tid');
                //删除判断
                layer.confirm('确认删除吗？', {
                    btn: ['确定','返回'] //按钮
                }, function(){
                    //确定删除，调接口
                    $.ajax({
                        url: '/workflow/work/deleteRunPrcs',
                        type: 'get',
                        dataType: 'json',
                        data:{
                            id:tid
                        },
                        beforeSend : function(request) {
                            if(beforeToken != ''){
                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                            }
                        },
                        success: function (obj) {
                            //第三方扩展皮肤
                            layer.msg('删除成功！', { icon:6});
                            if($.getQueryString("type") == 'EWC'){
                                window.history.go(-1);
                            }else{
                                /************调用移动端返回工作流列表方法************************/
                                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                                    try{
                                        window.webkit.messageHandlers.finishWork.postMessage({});
                                    }catch(err){
                                        finishWork();
                                    }
                                } else if (/(Android)/i.test(navigator.userAgent)) {
                                    Android.finishWebActivity();
                                }
                            }

                        }
                    })
                }, function(){
                    layer.closeAll();
                });
            });
            $('#content').on("input propertychange",'.calculation',function () {
                calcutarget($(this))

            });
            function calcutarget(__this) {
                var targetId = __this.attr('calcutarget');
                targetId = targetId.split(',');
                targetId.forEach(function (item,i) {
                    var targetObj = $('#'+item) ;
                    if(targetObj.attr('disabled') == 'disabled'){
                        return false;
                    }
                    var prec = targetObj.attr('prec')||0;
                    var calculationValue = targetObj.attr('formula');
                    var formitems = _this.tool.getFormDatasKeyValue();
                    formitems.forEach(function(v,i){
                        var calculateFlag = calculateFormitem(calculationValue,v.title);
                        if(calculationValue.indexOf(v.title) > -1&&calculateFlag){
                            if(v.value.indexOf('-')>-1){
                                var time = v.value.replace(/\-/g,'/');
                                calculationValue = calculationValue.replace(v.title,parseFloat(new Date(time).getTime()/1000));
                            }else{
                                if(v.value == ''){
                                    v.value = 0;
                                }
                                calculationValue = calculationValue.replace(v.title,v.value);
                            }
                        }
                    });
                    var result = '';
                    try {
                        result = eval(calculationValue);
                        if(parseFloat(result).toString() != 'NaN' && checkNumber(result)){
                            result = parseFloat(result).toFixed(prec);
                        }
                    }catch (e){
                        console.log(e);
                    }
                    targetObj.val(result).trigger('propertychange');
                });
            }
        },
        /************工作流 保存数据库的方法************************/
        saveFlowData:function (cb,isCheckOpt){
            layer.load();
            markFunc();
            var flowfun = globalData.flowRun;
            var isCheck = true;
            if(isCheckOpt && isCheckOpt=='noCheck'){
                isCheck = false;
            }
            var listing = false;
            var form_item=$('#content .form_item');
            var realData=[];
            var radioArr = {};
            var modifydata =[];
            var flag = false;
            var modifydataObject = {};
            var countersignData = '';
            var thisprcsItem = [],thisprcsItemAuto = [];
            if(globalData.flowProcesses){
                if(globalData.flowProcesses.prcsItem&&globalData.flowProcesses.prcsItem != ''){
                    var thisprcsItem = globalData.flowProcesses.prcsItem.split(',');
                }
                if(globalData.flowProcesses.prcsItemAuto&&globalData.flowProcesses.prcsItemAuto != ''){
                    var thisprcsItemAuto = globalData.flowProcesses.prcsItemAuto.split(',');
                }
            }
            for(var i=0;i<form_item.length;i++){
                var baseData={};
                var value="";
                var obj = form_item.eq(i);
                var datatype = obj.attr("data-type");
                var key=obj.attr("name");
                var ismust = obj.attr('ismust');
                var title = obj.attr('title')||'';
                if(datatype=="select"){
                    if(obj.val() == null){
                        value = '';
                    }else{
                        value= obj.val()==0?'':form_item.eq(i).val();
                    }
                }else if(datatype=="textarea"){
		            if(obj.hasClass('countersignature_item')) {
                        if(ismust == 'true'&&$('.countersignature_itemhide').length == 0){          //适用于设置了当前流程必填字段和当前流程转出条件的流程
                            $.layerMsg({content: '请签名!', icon: 1}, function(){
                                layer.closeAll();
                            });
                            return false;
                        }else{
                            saveCSNtr_item(obj);
                        }
                    }
                    value=obj.val();
                }else if(datatype=="text"  ){
                    value=obj.val();
                }else if(datatype=="markformItem"  ){
                    value=obj.val();
                }else if(datatype=="sign"){
                    var valueSign = obj.val().trim();
                    var pre = obj.prev();
                    countersignData += obj.attr('name')+',';
                    var $eiderarea = pre.find('.eiderarea').last();
                    if(valueSign){
                        $eiderarea.find('.remove_sign').css('display','none');
                        value = Mustache.render($eiderarea.prop("outerHTML"),{content:''});
                        // $eiderarea.each(function(index, ele){
                        //     var $ele = $($(ele).prop("outerHTML"));
                        //     $ele.find('.remove_sign').css('display','none');
                        //     value = Mustache.render($(ele).prop("outerHTML"),{content:''});
                        // });
                    }else{
                        // $eiderarea.each(function(index, ele){
                        //     var signHtml = $(ele).prop("outerHTML");
                        //     var content = signHtml.match(/>(\S*?)<br>/)[1];
                        //     if (content.indexOf('{{content}}') == -1 && content.trim() != '') {
                        //         var $ele = $($(ele).prop("outerHTML"));
                        //         $ele.find('.remove_sign').css('display','none');
                        //         value += Mustache.render($(ele).prop("outerHTML"),{content:''});
                        //     }
                        // });
                        value = "";
                    }
                }else if(datatype=="countersignature_item"){
                    if(ismust == 'true'&&$('.countersignature_itemhide').length == 0){          //适用于设置了当前流程必填字段和当前流程转出条件的流程
                        $.layerMsg({content: '请签名!', icon: 1});
                        setTimeout(function(){
                            layer.closeAll();
                        },1000)
                        return false;
                    }else{
                        saveCSNtr_item(obj);
                    }
                    value=obj.val();
                }else if(datatype == "macrossign"){
                    if (obj.attr('datafld') == 'SYS_FLOW_CONNECTFLOW' && obj.attr('flowtype') == 1){
                        value = obj.val();
                    } else {
                        value = obj.html();
                    }

                }else if(datatype=="checkbox"){
                    // value=obj.attr('title');
                    if(obj.is(':checked')){
                        value = '1';
                    }else{
                        value = '0';
                    }
                }else if(datatype=="macros"){
                    if(thisprcsItem.indexOf(title) > -1||thisprcsItemAuto.indexOf(title) > -1){
                        if(obj.attr('type') == "text"){
                            value= obj.val();
                            var datafld = obj.attr('datafld');
                            if(obj.attr('disabled') != 'disabled' || obj.hasClass('prcsItemAuto')){
                                if(obj.attr('datafld')=='SYS_USERNAME'&&obj.attr('orgsignImg')==1){
                                    if(obj.attr('signSrc')!=undefined&&obj.attr('signSrc')!=''&&obj.attr('signSrc').indexOf('AID')>=0){
                                        value = obj.attr('signSrc')
                                    }else{
                                        if(workForm.tool.getMacrosData(datafld)() != "" && (value=="" || value == '{macros}')){
                                            value = workForm.tool.getMacrosData(datafld)();
                                        }
                                    }

                                }else{
                                    if(workForm.tool.getMacrosData(datafld)() != "" && (value=="" || value == '{macros}')){
                                        value = workForm.tool.getMacrosData(datafld)();
                                    }
                                }

                            }else{
                                if(obj.attr('datafld')=='SYS_USERNAME'&&obj.attr('orgsignImg')==1){
                                    if(obj.attr('signSrc')!=undefined&&obj.attr('signSrc')!=''&&obj.attr('signSrc').indexOf('AID')>=0){
                                        value = obj.attr('signSrc')
                                    }else{
                                        if(workForm.tool.getMacrosData(datafld)() != "" && (value=="" || value == '{macros}')){
                                            value = workForm.tool.getMacrosData(datafld)();
                                        }
                                    }

                                }
                            }


                        }else if(obj.attr('type') == "select"){
                            //value = obj.val() == 0?'':form_item.eq(i).val();
                            value = obj.val()+'_'+obj.find("option:selected").text();
                        }else{
                            value = obj.val();
                        }
                    }else{
                        value = '';
                    }
                }else if(datatype == "radio"){
                    var name = obj.attr('name');
                    if(!radioArr[obj.attr('name')]){
                        radioArr[obj.attr('name')] = true;
                        if($("input[name='"+name+"']:checked").length>0){
                            value= $("input[name='"+name+"']:checked").val();
                        }else{
                            value = "";
                        }
                    }else{
                        continue;
                    }
                }else if(datatype == "imgupload"){
                    var name = obj.attr('name');
                    $('img[name='+name+']').each(function(i,v){
                        var url = $(v).attr('src')||'';
                        if(url.indexOf('/img/icon_uploadimg.png') == -1){
                            var str = url;
                            var strs = str.split('&ATTACHMENT_NAME=')[0];
                            var name = str.split('&ATTACHMENT_NAME=')[1].split('&FILESIZE=')[0];
                            var attName = decodeURI(name).replace(/\%2b/g, "+").replace(/\%40/g,"@").replace(/\%23/g,"#").replace(/\%26/g,"&").replace(/\%2F/g,"/").replace(/\%3F/g,"?").replace(/\%ef%bf%a5/g,"￥").replace(/\%24/g,"$").replace(/\%ef%bc%81/g,"！").replace(/\%ef%bc%88/g,"（").replace(/\%ef%bc%89/g,"）").replace(/\%e2%80%a6%e2%80%a6/g,"…");
                            var atturl =strs+"&ATTACHMENT_NAME="+attName+"&FILESIZE="+str.split('&ATTACHMENT_NAME=')[1].split('&FILESIZE=')[1];
                            if(atturl != undefined && atturl != '' && atturl.indexOf(',') > -1){
                                atturl = atturl.replace(/\,/g, "%2c");
                            }
                            value+= (atturl+'*');
                        }
                    })
                }else if(datatype == "fileupload"){
                    var name = obj.attr('name');
                    $('img[name='+name+']').each(function(i,v){
                        var url = $(v).attr('atturl');
                        var src = $(v).attr('src')||'';
                        if(src.indexOf('/img/fileupload.png') == -1){
                            if(url != undefined && url != '' && url.indexOf(',') > -1){
                                url = url.replace(/\,/g, "%2c");
                            }
                            value+= (url+'*');
                        }
                    })
                }else if(datatype == "kgsign"){
                    value = (obj.attr('signatureId') || '');
                }else if(datatype == "deptselect"){
                    if(obj.attr('deptname')){
                        value= (obj.attr('deptid') || '')+'|'+(obj.attr('deptname')||'');
                    }else{
                        value = obj.attr('deptname')||'';
                    }

                }else if(datatype == "userselect"){
                    if(obj.attr('user_id')){
                        value= (obj.attr('user_id')||'')+'|'+ (obj.attr('username')||'');
                    }else{
                        value = obj.attr('username')|| '';
                    }

                }else if(datatype == "listing"){
                    var vtrStr = [];
                    var vsumStr = [];
                    obj.find('tr').each(function(){
                        if($(this).attr('class') != 'listhead' && $(this).attr('class')!= 'listfoot'){
                            var  listTdObj = $(this).find('td');
                            if($(this).attr('class') == 'listsum'){
                                listTdObj.each(function (i,v) {
                                    var _this = $(v);
                                    if(_this.attr('class')!='sumtitle'){
                                        if(_this.html() !=''&&_this.html() !='0'){
                                            listing = true;
                                        }
                                        vsumStr.push(_this.html());
                                    }
                                });
                            }else{
                                var vtdStr = [];
                                listTdObj.each(function (i,v) {
                                    var _this = $(v);
                                    var listtype = $(v).attr('listtype');
                                    switch (listtype){
                                        case 'text':
                                            if(_this.find('input').val() !=''&&_this.find('input').val() !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push(_this.find('input').val());
                                            break;
                                        case 'textarea':
                                            if(_this.find('textarea').val() !=''&&_this.find('textarea').val() !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push(_this.find('textarea').val());
                                            break;
                                        case 'select':
                                            if(_this.find('select').val() !=''&&_this.find('select').val() !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push(_this.find('select').val());
                                            break;
                                        case 'radio':
                                            var name = _this.find('input').eq(0).attr('name');
                                            if($('input[name="'+name+'"]:checked').val() !=''&&$('input[name="'+name+'"]:checked').val() !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push($('input[name="'+name+'"]:checked').val());
                                            break;
                                        case 'checkbox':
                                            var checkboxStr = [];
                                            _this.find('input:checked').each(function(i,v){
                                                checkboxStr.push($(v).attr('value'));
                                            });
                                            if(checkboxStr.join(',') !=''&&checkboxStr.join(',') !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push(checkboxStr.join(','));
                                            break;
                                        case 'datetime':
                                            if(_this.find('input').val() !=''&&_this.find('input').val() !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push(_this.find('input').val());
                                            break;
                                        case 'dateAndTime':
                                            if(_this.find('input').val() !=''&&_this.find('input').val() !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push(_this.find('input').val());
                                            break;
                                        case 'formula':
                                            if(_this.text() !=''&&_this.text() !='0'){
                                                listing = true;
                                            }
                                            vtdStr.push(_this.text())
                                            break;
                                        default:
                                    }

                                });
                                vtrStr.push(vtdStr.join('`'))
                            }

                        }
                    });
                    value = vtrStr.join('\r\n') +'|'+vsumStr.join('`');

                }else if(datatype == "djsign"){
                    if(obj.val() != ''){
                        if(obj.val().indexOf('DATA_HW:') > -1&&obj.val().indexOf('DATA_SEAL:') > -1){
                            var hw = obj.val().split('DATA_HW:')[1].split('DATA_SEAL:')[0]||'';
                            var seal = obj.val().split('DATA_HW:')[1].split('DATA_SEAL:')[1]||'';
                            if(hw == ''&&obj.parent().siblings('.divDJBox').find('.hwImg').length != 0){
                                parseAppSeal(obj.parent().siblings('.divDJBox').find('.hwImg').attr('atturl'),obj.attr('id'),'hw','special');
                                hw = DATA_HW;
                                DATA_HW = '';
                            }
                            if(seal == ''&&obj.parent().siblings('.divDJBox').find('.sealImg').length != 0){
                                seal = obj.parent().siblings('.divDJBox').find('.sealImg').attr('atturl');
                            }
                            if(seal == 'undefined'){
                                seal = '';
                            }
                            if(hw == 'undefined'){
                                hw = '';
                            }
                            value = 'DATA_HW:'+hw+'DATA_SEAL:'+seal;
                        }else{
                            value = obj.val();
                        }
                    }else{
                        value = WebSign_Submit(obj.attr('name'));
                    }
                }else{
                    value = obj.val();
                }
                if(datatype == 'listing'){
                    if(!listing) {
                        value = '';
                    }
                }
                var isMustValue = value;
                // 判断会签意见是否填写
                if(datatype == 'sign'){
                    isMustValue = '';
                    // 获取输入框的值
                    var valueSign = obj.val().trim();

                    // 有值跳过
                    if(valueSign){
                        isMustValue = valueSign;
                    }else{ // 无值，需要判断当前用户当前步骤是否填写过意见
                        var pre = obj.prev();
                        var $eiderarea = pre.find('.eiderarea');
                        var flowRunPrcs = workForm.option.flowRunPrcs;
                        $eiderarea.each(function(index, ele){
                            if ($(this).attr('user_id') == flowRunPrcs.userId && $(this).attr('prcs_id') == flowRunPrcs.flowPrcs) {
                                var signHtml = $(ele).prop("outerHTML");
                                var contentArr = signHtml.split(/>/);
                                var content = contentArr[1].split(/</)[0];
                                // var content = signHtml.match(/>(\S*?)<br>/)[1];
                                if (content.indexOf('{{content}}') == -1 && content.trim() != '') {
                                    isMustValue += content
                                }
                            }
                        });
                    }
                }
                //针对复选框控件 value必须等于1或者0 所以需要特殊处理下必填条件下 value的值
                if(datatype=='checkbox'){
                    if(isMustValue=='0'){
                        isMustValue=''
                    }
                }
                //针对宏当前用户辅助角色控件 value在选择时 值为“undefined” 所以需要特殊处理下必填条件下 value的值
                else if(datatype=='macros'&&obj.attr('datafld')=='SYS_USERPRIVOTHER'){
                    if(!isMustValue){
                        isMustValue=''
                    }
                }
                //针对宏部门主管（上级部门）控件 value在选择时 值为“undefined” 所以需要特殊处理下必填条件下 value的值
                else if(datatype=='macros'&&obj.attr('datafld')=='SYS_MANAGER2'){
                    if(!isMustValue){
                        isMustValue=''
                    }
                }
                //针对宏值来自sql查询语句按角色控件 和 宏值来自sql查询语句按角色排序号控件 和 宏值来自sql查询语句按流水号控件 value在选择时 值为“undefined” 所以需要特殊处理下必填条件下 value的值
                else if(datatype=='macros'&&obj.attr('datafld')=='SYS_SQL'){
                    if(!isMustValue){
                        isMustValue=''
                    }
                }
                //针对宏来自SQL查询语句的列表控件 value在选择时 值为“null” 所以需要特殊处理下必填条件下 value的值
                else if(datatype=='macros'&&obj.attr('datafld')=='SYS_LIST_SQL'){
                    if(isMustValue==null){
                        isMustValue = '';
                    }
                }
                if(isCheck && ismust == 'true' && isMustValue == ""){     //适用于设置了当前流程必填字段的流程
                    if(gobackIndex != 1){                 //适用于设置了当前流程必填字段的流程，点击回退按钮兼容效果
                        flag = true;
                        // layer.msg('请填写'+obj.attr('title'));
                        layer.closeAll();
                        $.layerMsg({content: '请填写'+obj.attr('title')});
                        // setTimeout(function(){
                        //     layer.closeAll();
                        // },1000)
                        break;
                    }
                }
                //防止控件取值为null得判断 防止后台无法转交
                if(value == null){
                    value = '';
                }

                baseData["key"]=key;
                baseData["value"]=value;

                realData.push(baseData);
                if(thisprcsItem.indexOf(title) > -1||thisprcsItemAuto.indexOf(title) > -1){
                    modifydata.push(baseData);
                }
                modifydataObject[key] = value;
            }
            if(globalData.runname != ''){
                var datarunname = globalData.runname;
            }else{
                var datarunname = globalData.flowRun.runName;
            }
            /***************特殊的文号表达式功能start************************/
            if(datarunname!=''&&datarunname.indexOf('{FS') > -1&&datarunname.indexOf('FE}|[') > -1){
                var arr = datarunname.match(/\{FS[^\]]+\]/g);
                var sta = datarunname.split(arr[0])[0];
                var end = datarunname.split(arr[arr.length-1])[1];
                var str = '';
                for(var i=0;i<arr.length;i++){
                    if(arr[i].indexOf('['+ globalData.prcsId +']') > -1){
                        var title = arr[i].split('|[')[0].replace(/\{FS/g,'').replace(/\FE}/g,'');
                        if(modifydataObject[globalData.fromDataReject[title]]){
                            str += modifydataObject[globalData.fromDataReject[title]];
                        }
                    }else{
                        str += arr[i];
                    }
                }
                datarunname = sta+str+end;
            }
            /***************特殊的文号表达式功能end************************/
            if(!flag){
                var fdata={
                    flowId:globalData.flowId,
                    formdata:JSON.stringify(realData),
                    runId:globalData.flowRun.runId,
                    runName:datarunname,
                    beginTime:globalData.flowRun.beginTime,
                    beginUser:globalData.flowRun.beginUser,
                    formLength:globalData.option.formLength,
                    prcsId : globalData.flowStep,
                    flowPrcs : globalData.prcsId,
                    modifydata:JSON.stringify(modifydata),
                    fromDataReject:JSON.stringify(globalData.fromDataReject),
                    tableName:globalData.tableName,
                    tabId:globalData.tabId,
                    countersignData:countersignData
                };
                // if(typeof  Signature != 'undefined'){
                //     var list = Signature.list;
                //     var signatureCreator = Signature.create();
                //     var kgsignList=$('#content .kgsign');
                //     kgsignList.each(function(){
                //         //新增签章
                //         var key = $(this).attr('signatureid');
                //         if(list[key]){
                //             signatureCreator.saveSignature(flowfun.runId, key, list[key].getSignatureData());
                //         }
                //     });
                // }

                if(gobackIndex == 1){ //适用于设置了当前流程转出条件的流程，点击回退按钮兼容效果
                    $.ajax({
                        type: "post",
                        url: "../../workflow/work/nextwork",
                        dataType: 'JSON',
                        data: fdata,
                        beforeSend : function(request) {
                            if(beforeToken != ''){
                                request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                            }
                        },
                        success: function(res){
                            $('textarea[data-type=sign]').val('');
                            var data ={};
                            if(cb){
                                if(res.flag){
                                    data.flag = true;
                                }else{
                                    data.flag = false;
                                }
                                data.data = res.obj;
                                cb(data);
                            }
                        }
                    });
                }else{
                    if(savebtn){
                        $.ajax({
                            type: "post",
                            url: "../../workflow/work/nextwork",
                            dataType: 'JSON',
                            data: fdata,
                            beforeSend : function(request) {
                                if(beforeToken != ''){
                                    request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                                }
                            },
                            success: function(res){
                                $('textarea[data-type=sign]').val('');
                                var data ={};
                                savebtn = false;
                                if(cb){
                                    if(res.flag){
                                        data.flag = true;
                                    }else{
                                        data.flag = false;
                                    }
                                    data.data = res.obj;
                                    cb(data);
                                }
                            }
                        });
                    }else{
                        checkPrcOut(JSON.parse(fdata.formdata),JSON.parse(fdata.fromDataReject),function(res){
                            if(res.flag){
                                $.ajax({
                                    type: "post",
                                    url: "../../workflow/work/nextwork",
                                    dataType: 'JSON',
                                    data: fdata,
                                    beforeSend : function(request) {
                                        if(beforeToken != ''){
                                            request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                                        }
                                    },
                                    success: function(res){
                                        $('textarea[data-type=sign]').val('');
                                        var data ={};
                                        if(cb){
                                            if(res.flag){
                                                data.flag = true;
                                            }else{
                                                data.flag = false;
                                            }
                                            data.data = res.obj;
                                            cb(data);
                                        }
                                    }
                                });
                            }else{
                                $.layerMsg({content:res.msg,icon:0},function(){
                                       layer.closeAll();
                                });
                            }
                        });
                    }

                }
            }
        },
        /************工作流数据录入、判断方法************************/
        buildBody : function(data){
            var _this = (this);
            var target = data;
            var dataList = data.find('.form_item');
            if(workForm.option.snum){
                var k = workForm.option.snum.substr(5, 1);
                if(dataList.length == 0&& k == 'X'){
                    var s = '<div style="width: 90%;/* height: 150px; *//* margin: 135px auto; */background-color: #357ece;border-radius: 10px;box-shadow: 3px 3px 3px #2F5C8F;overflow: hidden;text-align: center;">\n' +
                        '        \n' +
                        '        <div class="TXT" id="TXT" style="float: left;color: #fff;font-size: 16pt;/* margin-top: 49px; *//* margin-left: 20px; */width: 306px;">该流程超过中小企业免费版表单控件数量限制，请联系管理员！</div>\n' +
                        '    </div>';
                    $('#content').append(s);
                    return false;
                }
            }
            var preObj = '';
            var tableObj = [];
            var idnum = 0;
            var checkidnum=0;   
            dataList.each(function(i,v) {
                var __this = $(this);
                var dataType = __this.attr('data-type');
                var title = __this.attr('title');
                var name = __this.attr('name');
                var isMust = __this.attr('isMust');
                object[name] = false;
                arrobject.push(name);
                var isMustText = '';
                if(isMust){
                    isMustText = '<span style="color:red;font-size: 20px;margin-left: 2px">*</span>';
                }

                var eleTrObj = $('<tr><td class="td1"><div>' + title + isMustText + '</div></td><td class="td2"></td></tr>');
                var e = {};
                if(__this.attr('secret') == 1){
                    __this.hide();
                    eleTrObj.find('.td2').append(__this).append('*****');
                }else{
                    switch (dataType) {
                        case 'text':
                            __this.addClass("gapp_input gapp_form");
                            __this.attr("style",'');
                            eleTrObj.find('.td2').append(__this);
                            break;
                        case 'markformItem':
                            eleTrObj.find('.td2').append(__this.parent().prop("outerHTML"));
                            break;
                        case 'calculation':
                            __this.addClass("gapp_input gapp_form");
                            __this.attr("style",'');
                            eleTrObj.find('.td2').append(__this);
                            break;
                        case 'textarea':
                            __this.addClass("gapp_textarea");
                            eleTrObj.find('.td2').append(__this);
                            eleTrObj.find('.td1').find('div').addClass('textareaclass');
                            break;
                        case 'countersignature_item':
                            __this.addClass("gapp_textarea");
                            __this.attr("style",'');
                            eleTrObj.find('.td2').append(__this);
                            eleTrObj.find('.td1').find('div').addClass('textareaclass');
                            break;
                        case 'select':
                            __this.addClass("gapp_select gapp_form");
                            __this.attr("style",'');
                            if(__this.attr('disabled')=='disabled'){
                                __this.css('background','url("/img/workflow/work/workformh5/select.png") no-repeat 95% 12px')
                                __this.css('background-color',' #f8f8f8!important')
                                __this.css('color',' #333!important')
                            }
                            eleTrObj.find('.td2').append(__this);
                            break;
                        case 'radio':
                            var bool=true;
                            for(var i=0;i<tableObj.length;i++){
                                if($(tableObj[i]).find('[name="'+__this.attr('name')+'"]').length!=0){
                                    bool=false;
                                }
                            }
                            if(bool) {
                                var radioObj = $('<span style="position: relative;width: 22px;height: 16px;display: inline-block"></span>');
                                var id = __this.attr('name');
                                __this.attr('id', id + '_' + idnum);
                                $(__this).css({
                                    'position': 'absolute',
                                    'top': '0',
                                    'left': '2px'
                                })
                                radioObj.append(__this)
                                var lable = '<label style="left: 0;top: 0;" class="bgweijinyong" for="' + id + '_' + idnum + '"></label>';
                                if(__this.attr('disabled')=='disabled') {
                                    lable = '<label style="left: 0;top: 0;" class="bgyijingyong" for="' + id + '_' + idnum + '"></label>';
                                }
                                radioObj.append(lable);
                                var special = $('<div></div>');
                                special.append(radioObj);
                                special.append('<span  style="height: 36px;line-height: 36px;display: inline-block;padding-left: 5px;' +
                                    'padding-right: 15px;">' + __this.val() + '</span>');
                                eleTrObj.find('.td2').append(special);
                                // eleTrObj.find('.td2')
                                //     .append('<span  style="line-height: 22px;display: inline-block;padding-left: 5px;' +
                                //         'padding-right: 15px;">' + __this.val() + '</span>')
                                idnum++;
                            }else {
                                eleTrObj=$('');
                                for(var i=0;i<tableObj.length;i++){
                                    if($(tableObj[i]).find('[name="'+__this.attr('name')+'"]').length!=0){
                                        var tableObjParent=$(tableObj[i]).find('[name="'+__this.attr('name')+'"]').parent().parent().parent();
                                        var radioObj = $('<span style="position: relative;width: 22px;height: 16px;display: inline-block"></span>');
                                        var id = __this.attr('name');
                                        __this.attr('id', id + '_' + idnum);
                                        $(__this).css({
                                            'position': 'absolute',
                                            'top': '0',
                                            'left': '2px'
                                        })
                                        radioObj.append(__this)
                                        var lable = '<label style="left: 0;top: 0;" class="bgweijinyong" for="' + id + '_' + idnum + '"></label>';
                                        if(__this.attr('disabled')=='disabled') {
                                            lable = '<label style="left: 0;top: 0;" class="bgyijingyong" for="' + id + '_' + idnum + '"></label>';
                                        }
                                        radioObj.append(lable);
                                        var special = $('<div></div>');
                                        special.append(radioObj);
                                        special.append('<span  style="height: 36px;line-height: 36px;display: inline-block;padding-left: 5px;' +
                                            'padding-right: 15px;">' + __this.val() + '</span>')

                                        tableObjParent.append(special);
                                        // tableObjParent.append('<span  style="line-height: 22px;display: inline-block;padding-left: 5px;' +
                                        //         'padding-right: 15px;">' + __this.val() + '</span>')
                                    }
                                }
                                idnum++;
                            }

                            break;
                        case 'checkbox':
                            var id = __this.attr('name');
                            __this.attr('id',id+'_'+checkidnum);
                            eleTrObj.find('.td2').append(__this);
                            var lable = '<label class="bgweijinyong" style="border-radius: 0px" for="'+ id+'_'+checkidnum +'"></label>';
                            if(__this.attr('disabled')=='disabled'){
                                lable = '<label class="bgyijingyong" style="border-radius: 0px" for="'+ id+'_'+checkidnum +'"></label>';
                            }
                            eleTrObj.find('.td2').append(lable);
                            checkidnum++;
                            break;
                        case 'qrcode':
                            __this.css("float","none");
                            eleTrObj.find('.td2').append(__this);
                            break;
                        case 'kgsign':

                            $(__this.find("img").get(0)).attr("style","cursor: pointer; margin: 0 auto;width:100%;height:100%;")
                            eleTrObj.find('.td2').append(__this);
                            break;
                        case 'macros':
                            if(__this.val() == '{macros}'){
                                __this.val(workForm.tool.getMacrosData(__this.attr('datafld'))());
                            }
                            __this.addClass("gapp_input gapp_form");
                            __this.attr("style",'');
                            eleTrObj.find('.td2').html('');
                            if(__this.attr('datafld')=='SYS_USERNAME'&&__this.attr('orgsignImg')==1){
                                if(__this.attr('signSrc')!=""&&__this.attr('signSrc')!=undefined&&__this.attr('signSrc').indexOf('AID')>=0){
                                    var signSpan = '<span><img style="width:100px;height:auto" src="'+__this.attr('signSrc')+'" alt=""></span>';
                                    __this.css('display','none')
                                    eleTrObj.find('.td2').append(signSpan);
                                }
                            }
                            eleTrObj.find('.td2').append(__this);
                            if(__this.attr('title') == '标题'){
                                var OBj = $('<textarea name="'+ __this.attr('id') +'" /' +
                                    'type="text" value="测试公111111111" class="'+ __this.attr('class') +'" /' +
                                    'data-type="macros" title="标题" id="'+ __this.attr('id') +'" datafld="'+ __this.attr('datafld') +'" /' +
                                    'style="'+ function(){
                                        if(__this.attr('style') == undefined){
                                            return '';
                                        }else{
                                            return __this.attr('style')+';';
                                        }
                                    }() +'color: rgb(17, 17, 17);width: calc(100% - 20px);padding: 10px;">'+ __this.val() +'</textarea>');
                                eleTrObj.find('.td2').html(OBj);
                                var dis = __this.attr('disabled');
                                if(dis == 'disabled'){
                                    OBj.css({
                                        'background-color':'#f8f8f8',
                                        'color':'#000'
                                    })
                                    OBj.attr('disabled','disabled').addClass('grey').parents('tr').find('.td1').addClass('grey1');
                                }else {
                                    OBj.css('color','#111')
                                }
                                OBj.css("height", OBj.scrollHeight + "px");
                            }
                            break;
                        case 'calendar':
                            __this.addClass("gapp_input gapp_date").removeClass('laydate-icon');
                            __this.attr("style",'padding-right: 0px;');
                            __this.attr("dates_format",__this.attr("date_format"));
                            if($.getQueryString("type") != 'EWC'){
                                __this.attr("onclick","timeclick($(this))");
                            }
                            __this.removeAttr("date_format");
                            eleTrObj.find('.td2').append(__this);
                            break;
                        case 'imgupload':
                            data.find('img[name="'+name+'"]').each(function (i,v) {
                                if($(v).attr("src") != undefined&&$(v).attr("src").indexOf('/img/icon_uploadimg.png') == -1){
                                    $(v).attr('url',$(v).attr('src'));
                                    $(v).attr('src',decodeURI($(v).attr('src')));
                                    $(v).attr('names',$(v).attr('url').split('&ATTACHMENT_NAME=')[1].split('&FILESIZE=')[0]);
                                    $(v).attr('onclick','anios1($(this))');
                                    if($(v).attr('disabled')!='disabled'){
                                        var thisspan = decodeURI($(v).attr("names"));
                                        thisspan = decodeURI(thisspan).replace(/\%2b/g, "+").replace(/\%40/g,"@").replace(/\%23/g,"#").replace(/\%26/g,"&").replace(/\%2F/g,"/").replace(/\%3F/g,"?").replace(/\%ef%bf%a5/g,"￥").replace(/\%24/g,"$").replace(/\%ef%bc%81/g,"！").replace(/\%ef%bc%88/g,"（").replace(/\%ef%bc%89/g,"）").replace(/\%e2%80%a6%e2%80%a6/g,"…");
                                        var attachname = thisspan;
                                        if(thisspan.split('.')[0].length > 8){
                                            var thisspan = thisspan.split('.')[0].substr(0,8)+'…'+thisspan.split('.')[1];
                                        }
                                        $(v).attr('url',$(v).attr('src').split('&ATTACHMENT_NAME=')[0]+'&ATTACHMENT_NAME='+ attachname + '&FILESIZE=' +$(v).attr('src').split('&ATTACHMENT_NAME=')[1].split('&FILESIZE=')[1]);
                                        eleTrObj.find('.td2').css({
                                            'padding-top': '5px',
                                            'padding-bottom': '5px'
                                        }).append('<div class="imgfileBox" style="display:  inline-block;position:  relative;float: left;">'+ v.outerHTML +'<span class="uploadImg">'+ thisspan +'</span></div>');
                                    }
                                }else{
                                    if($(v).attr('disabled')!='disabled'){
                                        $(v).attr("onclick","phoneimgupload(this)");

                                    }else{
                                        $(v).css('display','none');
                                        if(i != 0){
                                            eleTrObj.find('.td2').append('');
                                        }else{
                                            eleTrObj.find('.td2').append('无');
                                        }
                                    }
                                    eleTrObj.find('.td2').append(v);
                                }
                            });
                            break;
                        case 'fileupload':
                            data.find('img[name="'+name+'"]').each(function (i,v) {
                                if($(v).attr("src") != undefined&&$(v).attr("src").indexOf('/img/fileupload.png') == -1&&$(v).attr("src").indexOf('/img/icon_uploadimg.png') == -1&&$(v).attr('atturl') != undefined){
                                    $(v).attr('url',$(v).attr('atturl'));
                                    $(v).attr('names',$(v).attr('url').split('&ATTACHMENT_NAME=')[1].split('&FILESIZE=')[0]);
                                    $(v).attr('onclick','anios1($(this))');
                                    if($(v).attr('disabled')!='disabled'){
                                        var thisspan = $(v).attr("names");
                                       /* if(thisspan.split('.')[0].length > 8){
                                            var thisspan = thisspan.split('.')[0].substr(0,8)+'…'+thisspan.split('.')[1];
                                        }*/
                                        eleTrObj.find('.td2').css({
                                            'padding-top': '5px',
                                            'padding-bottom': '5px'
                                        }).append('<div class="imgfileBox" style="display:  inline-block;position:  relative;float: left;">'+ v.outerHTML +'<span class="uploadImg">'+ thisspan +'</span></div>');
                                    }
                                }else{
                                    if($(v).attr('disabled')!='disabled'){
                                        $(v).attr("onclick","phoneimgupload(this)");

                                    }else {
                                        $(v).css('display','none');
                                        if(i != 0){
                                            eleTrObj.find('.td2').append('');
                                        }else{
                                            eleTrObj.find('.td2').append('无');
                                        }
                                    }
                                    eleTrObj.find('.td2').append(v);
                                }
                            });
                            break;
                        case 'sign':
                            __this.addClass("gapp_textarea");
                            __this.attr("style",'');
                            var height = __this.prev().height();
                            if(!height){
                                height = 0;
                            }
                            __this.prev().css({'width':'auto','height':'auto','min-height':height+'px'});
                            eleTrObj.find('.td2').append(__this.prev());
                            eleTrObj.find('.td2').append(__this);
                            if (!$(__this).prop('disabled')) {
                                __this.after('<img src="/img/workflow/form/icon_countersign.png" id="addsignImg" onclick="addsignImg(this)" style="position: absolute;right: 5px;cursor: pointer;bottom: 30px;width: 24px;height: 24px;" />')
                            } else {
                                eleTrObj.find('.td2').find('.eiderarea').last().hide()
                                __this.hide()
                            }
                            eleTrObj.find('.td1').find('div').addClass('textareaclass');
                            break;
                        case 'readcomments':
                            __this.addClass("gapp_textarea");
                            __this.attr("style",'');
                            eleTrObj.find('.td2').append(__this);
                            eleTrObj.find('.td1').find('div').addClass('textareaclass');
                            break;
                        case 'listing':
                            __this.addClass("gapp_textarea");
                            __this.hide();
                            eleTrObj.find('.td2').append(__this);
                            eleTrObj.find('.td2').append('<input id="'+__this.attr('id')+'" class=" gapp_input gapp_form grey" disabled="disabled" "><img class="btn_list" src="/img/workflow/m/list.png" style="position: absolute; top: 50%;width: 25px!important; height: 25px!important;right: 15px;margin-top: -6px!important;">');
                            // eleTrObj.find('.td2').append('<textarea  class="form_item gapp_textarea grey" gwidth="200" gheight="50" style="background-color: rgb(228, 228, 228); color: rgb(0, 0, 0);" disabled="disabled"></textarea>');
                            eleTrObj.find('.td1').find('div').addClass('textareaclass');
                            break;
                        case 'userselect':
                            __this.addClass("gapp_textarea");
                            __this.attr("style",'');
                            var userselectClass = 'form_item  gapp_textarea userselect';
                            if(__this.attr('disabled') != 'disabled'){
                                userselectClass = userselectClass +' userselecth5';
                            }else{
                                userselectClass+=' grey'
                            }

                            var textareaObj = $('<textarea name="'+__this.attr('name')+'" ismust="'+__this.attr('ismust')+'" id="'+__this.attr('id')+'" class="'+userselectClass+'" data-type="userselect" title="'+__this.attr('title')+'" readonly="readonly" orgfontsize="'+__this.attr('orgfontsize')+'" orgwidth="'+__this.attr('orgwidth')+'" orgheight="'+__this.attr('orgheight')+'" user_id="'+ (__this.attr('user_id') || '')+'" username="'+(__this.attr('username') || '')+'" style="'+__this.attr('style')+'"></textarea>');
                            textareaObj.val(__this.attr('username'));
                            eleTrObj.find('.td2').append(textareaObj);

                            eleTrObj.find('.td1').find('div').addClass('textareaclass');
                            break;
                        case 'deptselect':
                            __this.addClass("gapp_textarea");
                            __this.attr("style",'');
                            var userselectClass = 'form_item  gapp_textarea deptselect';
                            if(__this.attr('disabled') != 'disabled'){
                                userselectClass = userselectClass +' deptselecth5';
                            }else{
                                userselectClass+=' grey'
                            }
                            eleTrObj.find('.td2').append('<textarea name="'+__this.attr('name')+'" ismust="'+__this.attr('ismust')+'" id="'+__this.attr('id')+'" class="'+userselectClass+'" data-type="deptselect" title="'+__this.attr('title')+'" readonly="readonly" orgfontsize="'+__this.attr('orgfontsize')+'" orgwidth="'+__this.attr('orgwidth')+'" orgheight="'+__this.attr('orgheight')+'" deptid="'+ (__this.attr('deptid') || '')+'" deptname="'+(__this.attr('value') || '')+'" value="'+(__this.attr('value') || '')+'" style="'+__this.attr('style')+'">'+(__this.attr('value') || '')+'</textarea>');
                            eleTrObj.find('.td1').find('div').addClass('textareaclass');
                            break;
                        case 'autocode':
                            __this.addClass('gapp_input gapp_form');
                            __this.attr("style",'');
                            __this.attr('readonly',"readonly");
                            var targetid =  __this.attr('id');
                            eleTrObj.find('.td2').append(__this);
                            // eleTrObj.find('.td2').append('<span class="autospan" target="'+targetid+'" onclick="autoclik($(this))">赋值</span>');
                            break;
                        case 'macrossign':
                            var datafld = __this.attr('datafld');
                            if(datafld == "SYS_FLOW_SIGNTEXT"){
                                var textvalue = ''
                                if(__this.html().indexOf('{宏标记-会签控件}') == -1){
                                    textvalue = __this.html();
                                }
                                eleTrObj.find('.td2').append('<div class="form_item gapp_textarea grey" name="'+__this.attr('name')+'" id="'+__this.attr('id')+'" data-type="macrossign" datafld="'+__this.attr('datafld')+'"  gwidth="200" gheight="50" style="overflow-x: auto;background:#f8f8f8!important ;color: rgb(0, 0, 0);" disabled="disabled">'+textvalue+'</div>');
                            } else if (datafld == "SYS_FLOW_EXPLAINFILE") {
                                var value = '<span id="'+__this.attr('id')+'" explainFile="'+__this.attr('explainFile')+'" name="'+__this.attr('name')+'" data-type="macrossign" title="'+__this.attr('title')+'" datafld="'+__this.attr('datafld')+'" class="form_item macrossign">'+__this.html()+'</span>';
                                eleTrObj.find('.td2').append(value);
                            } else if (datafld == "SYS_FLOW_CHILDFLOW") {
                                var value = '<span id="'+__this.attr('id')+'" name="'+__this.attr('name')+'" data-type="macrossign" title="'+__this.attr('title')+'" datafld="'+__this.attr('datafld')+'" class="form_item macrossign">'+__this.html()+'</span>';
                                eleTrObj.find('.td2').append(value);
                            } else if (datafld == "SYS_FLOW_CONNECTFLOW") {
                                if (__this.attr('flowtype') == 1) {
                                    __this.attr('style', '');
                                    __this.attr('class', 'form_item macrossign gapp_input gapp_form');
                                }
                                eleTrObj.find('.td2').append(__this);
                            } else if (datafld == "SYS_NEWS") {
                                var value = '<span id="'+__this.attr('id')+'" name="'+__this.attr('name')+'" data-type="macrossign" title="'+__this.attr('title')+'" datafld="'+__this.attr('datafld')+'" class="form_item macrossign">'+__this.html()+'</span>';
                                eleTrObj.find('.td2').append(value);
                            } else {
                                eleTrObj.find('.td2').append('<input name="'+__this.attr('name')+'" id="'+__this.attr('id')+'" data-type="macrossign" title="'+__this.attr('title')+'" datafld="'+__this.attr('datafld')+'" class="form_item macrossign gapp_input gapp_form grey" disabled="disabled" value="'+ __this.html() +'">');
                            }
                            break;
                        case 'djsign':
                            eleTrObj.find('.td2').append('<div class="divDJBox"></div>');
                            eleTrObj.find('.td2').append(__this.parent().eq(0));
                            break;
                        case 'writeSign':
                            // eleTrObj.find('.td2').append('<div class="divDJBox"></div>');
                            eleTrObj.find('.td2').append(__this.parent().eq(0));
                            break;
                        case 'extdataselect':
                            var id=__this.eq(0).attr("id").split("_")[1];
                            __this.eq(0).attr("onclick","extdataselectApp(1,"+id+")");
                            eleTrObj.find('.td2').append(__this.eq(0));
                            break;
                        case 'dataselect':
                            var id=__this.eq(0).attr("id").split("_")[1];
                            __this.eq(0).attr("onclick","extdataselectApp(2,"+id+")");
                            eleTrObj.find('.td2').append(__this.eq(0));
                            break;
                        default:
                    }
                }

                var isHidden = $(this).attr("orghidden");
                if(1 == isHidden || 'hidden' == isHidden){
                    $(this).parent().parent().hide();
                }
                // if(__this.attr('hidden') == 'hidden'){
                //     $(this).parent().append('*********');
                // }
                var dis = __this.attr('disabled');
                if(dis == 'disabled'){
                    __this.css({
                        'background-color':'#f8f8f8',
                        'color':'#000'
                    })
                    __this.addClass('grey').parents('tr').find('.td1').addClass('grey1');
                    var _this = $(this);
                    if(__this.attr('data-type') == "calendar"){
                        if(_this.attr('class').indexOf('grey') != -1){
                            _this.removeAttr('onclick');
                        }
                    }else if(__this.attr('data-type') == 'autocode'){
                        _this.next().remove();
                    }
                    
                } else {
                    __this.css('color','#111');
                }
                
                tableObj.push(eleTrObj);
            });
            $('#content').append(tableObj);
            $('#content').find('.qrcode').each(function () {
                var _this = $(this);
                var msg = {"mark":"SID_MEETING","url":_this.attr('textstr')};
                var id = _this.attr('id')
                var qrcode = new QRCode(id, {
                    text: JSON.stringify(msg),
                    width: _this.attr('orgwidth'),
                    height: _this.attr('orgheight'),
                    colorDark : '#000000',
                    colorLight : '#ffffff',
                    correctLevel : QRCode.CorrectLevel.H
                });
            });
            // if(typeof  Signature != 'undefined'){
            //     var signatureCreator = Signature.create();
            //     signatureCreator.getSaveSignatures( globalData.flowRun.runId, function(signs){
            //         var signdata = new Array();
            //         var jsonList = eval("("+signs+")");
            //         for(var i=0;i<jsonList.length;i++){
            //             var map = {};
            //             map.signatureid = jsonList[i]["signatureId"];
            //             map.signatureData = jsonList[i]["signature"];
            //             signdata.push(map);
            //         }
            //         console.log(signdata);
            //         Signature.loadSignatures(signdata);
            //     });
            // }
            globalData.fromDataReject = _this.buildFormData();
        },
        buildFormData : function(){
            var arr = {};
            $("#content").find('.form_item').each(function(i,v){
                var _this = $(this);
                arr[_this.attr('title')] = _this.attr('name');
            });
            return arr;
        },
        tool:{
            ajaxHtml:function (url,data,cb) {
                var that = this;
                $.ajax({
                    type: "get",
                    url: url,
                    async:false,
                    dataType: 'JSON',
                    data:  data,
                    beforeSend : function(request) {
                        if(beforeToken != ''){
                            request.setRequestHeader("Authorization", 'Bearer '+beforeToken);
                        }
                    },
                    success: function (res) {
                        if(cb){
                            cb(res);
                        }
                    },
                    error:function(e){

                    }
                });
            },
            getFormDatasKeyValue:function(){
                var radioArr = {};
                var formitems = [];
                var form_item = $('#content').find('.form_item');
                for(var i=0;i<form_item.length;i++){
                    var value="";
                    var obj = form_item.eq(i);

                    var datatype = obj.attr("data-type");
                    var key=obj.attr("title");
                    if(datatype=="select"){
                        value= obj.val()==0?'':form_item.eq(i).val();
                    }else if(datatype=="textarea" || datatype=="text"  ){
                        value=obj.val();
                    }else if(datatype=="checkbox"){
                        if(obj.is(':checked')){
                            value = '1';
                        }else{
                            value = '0'
                        }
                    }else if(datatype=="macros"){
                        if(obj.attr('type') == "text"){
                            if(obj.attr('datafld')=='SYS_USERNAME'&&obj.attr('orgsignImg')==1){
                                if(obj.attr('signSrc')!=undefined&&obj.attr('signSrc')!=''&&obj.attr('signSrc').indexOf('AID')>=0){
                                    value = obj.attr('signSrc')
                                }else{
                                    value= obj.val();
                                }

                            }else{
                                value= obj.val();
                            }

                        }else{
                            if(obj.val() > -1){
                                value = obj.val()+'_'+obj.find("option:selected").text();
                            }
                        }
                    }else if(datatype == "radio"){
                        var name = obj.attr('name');
                        if(!radioArr[obj.attr('name')]){
                            radioArr[obj.attr('name')] = true;
                            if($("input[name='"+name+"']:checked").length>0){
                                value= $("input[name='"+name+"']:checked").val();
                            }else{
                                value = "";
                            }
                        }else{
                            continue;
                        }
                    }else if(datatype == "macrossign"){
                        value= obj.html();

                    }else if(datatype == "fileupload"){

                    }else if(datatype == "imgupload"){

                    }else if(datatype == "sign"){


                    }else if(datatype == "userselect"){
                        if(obj.attr('user_id')){
                            value= (obj.attr('user_id')||'')+'|'+ (obj.attr('username')||'');
                        }else{
                            value = obj.attr('username')||''
                        }

                    }else if(datatype == "deptselect"){
                        value= (obj.attr('deptid') || '')+'|'+(obj.attr('deptname')||'');
                    }else if(datatype == "kgsign"){
                        value = (obj.attr('signatureId') || '');
                    }else if(datatype == "listing"){

                    }else if(datatype == 'readcomments'){
                        value = obj.val();
                    }else{
                        value = obj.val();
                    }
                    var item = {
                        value:value,
                        id:obj.attr('id'),
                        title:obj.attr('title')
                    }
                    formitems.push(item);
                };
                return formitems;
            }

        }
    }

    /************调用工作流初始化方法************************/
    workformh5.init(function(){
        turn = function(){
            workformh5.turnH5Btn();
        }
    });

    // 添加经办人
    $('#addSign').click(function () {
        savebtn = true;
        workformh5.saveFlowData(function (res) {
            layer.closeAll();
            if (res.flag) {
                var content = $('.signBox .gapp_textarea').val();
                if (content != "") {
                    $.ajax({
                        type: "get",
                        url: "../../workflow/work/workfeedback",
                        dataType: 'JSON',
                        data: {
                            prcsId: globalData.prcsId,
                            runId: globalData.flowRun.runId,
                            flowPrcs: globalData.flowPrcs,
                            content: content,
                            file: '',
                            feedFlag: '0'
                        },
                        beforeSend: function (request) {
                            if (beforeToken != '') {
                                request.setRequestHeader("Authorization", 'Bearer ' + beforeToken);
                            }
                        },
                        success: function (res) {

                        }
                    })
                }
                layer.open({
                    type: 1,
                    // offset: '80px',
                    area: ['90%', '50%'],
                    closeBtn: 2,
                    title: '增加经办人',
                    content: '<div class="modal-body">' +
                        '<div>' +
                        '<div style="display: flex;justify-content: space-around;padding: 10px;">' +
                        '<textarea readonly disabled name="sign" id="sign" user_id="" style="width: 80%;height: 80px;"></textarea>' +
                        '<div style="display: flex;flex-direction: column;justify-content: space-evenly;"><a href="javascript:;" class="choose" style="color: #1687cb;padding:0px 10px">选择</a><a href="javascript:;" style="color: #ff5722;padding: 0px 10px;" class="empty">清空</a></div>' +
                        '</div>' +
                        '<div style="margin-top: 20px;border: 1px solid #e1e1e8;border-radius: 6px">' +
                        '<div class="signmsg" style="line-height: 32px;background-color: #f3f3f3;border-bottom:1px solid #e1e1e8;font-weight:bold;padding-left: 10px;">当前办理人信息</div>' +
                        '<div style="padding-left: 10px;color:green;line-height:28px"><span class="signUser"></span></div>' +
                        '</div>' +
                        '</div>' +
                        '</div>',
                    btn: ['确认', '取消'],
                    success: function (layero, index) {
                        $.ajax({
                            url: '/workflow/work/getFlowRunPrecsUser',
                            dataType: 'json',
                            type: 'get',
                            data: {
                                runId: globalData.runId,
                                prcsId: globalData.flowRunPrcs.prcsId,
                                flowPrcs: globalData.prcsId
                            },
                            success: function (res) {
                                if (res.flag) {
                                    if (res.object.length > 0) {
                                        var str = '' + globalData.flowRunPrcs.userName + '，'
                                        for (var i = 0; i < res.object.length; i++) {
                                            str += '<span class="signUsers">' + res.object[i].userName + '，</span>'
                                        }
                                        $('.signUser').html(str)
                                    }
                                }
                            }
                        })

                        // 选择会签人
                        $('.choose').click(function () {
                            user_id = 'sign'
                            selectUsreLayerIndex = layer.open({
                                title: '选择用户',
                                type: 2,
                                content: '/common/selectUser',
                                area: ['100%', '70%']
                            });
                        })

                        // 清空会签人
                        $('.empty').click(function () {
                            $('#sign').val('')
                            $('#sign').attr('user_id', '')
                        })

                    },
                    yes: function (index, layero) {
                        var textVal = $('#sign').val()
                        var str = ""
                        $('.signUsers').each(function (i, v) {
                            if (textVal.indexOf($(this).html().replace('，', '')) > -1) {
                                str += $(this).html()
                            }
                        })
                        if (textVal.indexOf($('.zUser').html()) > -1) {
                            str += $('.zUser').html() + ','
                        }

                        if (!$('#sign').attr('user_id')) {
                            $.layerMsg({content: '请选择经办人', icon: 2})
                            return false;
                        } else {
                            var index = layer.load(1);
                            $.ajax({
                                url: '/workflow/work/addFeedback',
                                data: {
                                    runId: globalData.runId,
                                    flowId: globalData.flowId,
                                    flowPrcs: globalData.prcsId,
                                    prcsId: globalData.flowRunPrcs.prcsId,
                                    runName: globalData.flowRun.runName,
                                    userId: $('#sign').attr('user_id'),
                                    topFlag: globalData.flowRunPrcs.topFlag
                                },
                                success: function (res) {
                                    if (res.flag) {
                                        $.ajax({
                                            url: '/workflow/work/getFlowRunPrecsUser',
                                            dataType: 'json',
                                            type: 'post',
                                            data: {
                                                runId: globalData.runId,
                                                prcsId: globalData.flowRunPrcs.prcsId,
                                                flowPrcs: globalData.prcsId
                                            },
                                            success: function (datas) {
                                                if (datas.flag) {
                                                    $.layerMsg({content: '添加成功', icon: 1})
                                                    layer.closeAll();
                                                    window.location.reload();
                                                }
                                            }
                                        })
                                    } else {
                                        $.layerMsg({content: '添加失败', icon: 2})
                                    }
                                }
                            });
                        }
                    }
                });
            } else {
                $.layerMsg({content: "保存失败！", icon: 2}, function () {

                });
            }
        }, 'noCheck');
    });
    
    // 显示交办
    $('#assignment').click(function(){
        workformh5.saveFlowData(function(res){
            layer.closeAll();
            if (res.flag) {
                if (globalData.feedback == 0) {
                    $('input[name="opinionType"]', $('#assignmentContent')).eq(0).prop("checked", true)
                    $('input[name="opinionType"]', $('#assignmentContent')).eq(1).attr("disabled", false)
                } else if (globalData.feedback == 1) {
                    $('input[name="opinionType"]', $('#assignmentContent')).eq(0).prop("checked", false)
                    $('input[name="opinionType"]', $('#assignmentContent')).eq(1).prop("checked", true)
                }
        
                $('#assignmentBox').show();
                $('#assignmentBox').siblings().hide();
            } else {
                $.layerMsg({content: '保存失败', icon: 2});
            }
        })
    })
});